【问题标题】:How to write a json file which contains two arraylists<String>如何编写一个包含两个 arraylists<String> 的 json 文件
【发布时间】:2017-03-08 18:43:13
【问题描述】:

我必须从 JSON 文件读取两个数组列表,其中一个包含问题,第二个包含答案,但我不知道如何编写该文件。这将是一个简单的测验。谁能给我一个例子

【问题讨论】:

  • 看看这里:stackoverflow.com/q/2591098/5810051。可能重复
  • 什么都没有,因为我不知道它应该是什么样子。这只是我的课程的一个程序,我的老师没有解释任何内容

标签: java json string arraylist


【解决方案1】:

也许是这样的?

{
   "questions":
   [
        "What is the capital of France?",
        "What is the answer to everything?"
   ],
   "answers":
   [
        "Paris", 
        "forty-two"
   ]
}

另一种方法是捆绑问答对:

[
   {
     "q": "What is the capital of France?",
     "a": "Paris" 
   },
   {
     "q": "What is the answer to everything?",
     "a": "42" 
   }
]

这取决于你的应用程序哪种方式更方便和自然。

【讨论】:

  • 明白你的意思,所以如果我有下一个问题和 aswear 只需要在逗号后添加?
  • 不,你会扩展列表。将更新我的答案。
【解决方案2】:
{
 "questions":["Question1","Question2","Question3"],
 "answers":["Answer1","Answer2","Answer3"]
}

我建议你创建一个简单的类来从对象生成 Json

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaToJson
{
  public static void main(String[] args) throws IOException
  {

    ArrayList<String> test = new ArrayList<String>();
    test.add("Question1");
    test.add("Question2");

    try
    {
        String jsonStr = new ObjectMapper().writeValueAsString(test);
        System.out.println("test: "+jsonStr);
    }
    catch (JsonProcessingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}

因此变量“jsonStr”将是您要查找的 json。

【讨论】:

    猜你喜欢
    • 2013-12-05
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多