我必须从JSON文件读取两个arraylist,其中一个包含问题,第二个包含答案,但我不知道如何编写该文件。这将是一个简单的测验。谁能给我一个例子
答案 0 :(得分:0)
也许是这样的?
{
"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"
}
]
这取决于您的应用哪种方式更方便和自然。
答案 1 :(得分:0)
{
"questions":["Question1","Question2","Question3"],
"answers":["Answer1","Answer2","Answer3"]
}
我建议你创建一个简单的类来从Object
生成Jsonimport 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。