我有一个json字符串,如下所示
[{"question":"Test Queston 1 ?","option1":null,},{"question":"Test Question 2 ?","option1":null}]
我想将“问题”对象分配给String [] questions_list。我怎样才能遍历这个json对象?
答案 0 :(得分:1)
您可以使用JSON.org Java Library。只需将库添加到项目中即可。如果您使用Maven,可以从此处添加依赖项:Maven Repository。 源代码也可在GitHub上获得。可以找到文档here.
然后你可以这样做:
JSONArray questionsArray = new JSONArray("[{"question":"Test Queston 1 ?","option1":null,},{"question":"Test Question 2 ?","option1":null}]");
for (int i = 0; i < questionsArray.length();, i++){
JSONObject questionJSON = questionsArray.get(i);
String questionName = questionJSON.get("question");
String option1 = question.JSON.get("option1");
//And so on
}
答案 1 :(得分:0)
如果我理解你的问题,你想将你的JSON转换为java数组。
以下是我写过的非常基本的测试:
import java.io.StringReader;
import javax.json.*;
public class JsonTest {
/**
* @param args
*/
public static void main(String[] args) {
String s="[{\"year\":\"2015\",\"org\":\"1\",\"sub_org\":\"2\",\"sub_org_amt\":\"1\"}," +
"{\"year\":\"2016\",\"org\":\"2\",\"sub_org\":\"3\",\"sub_org_amt\":\"1\"}]";
StringReader reader=new StringReader(s);
JsonReader r=Json.createReader(reader);
JsonArray a=r.readArray();
String ar[]=new String[a.size()];
for(int i=0;i<a.size();i++){
ar[i]=a.getJsonObject(i).toString();
System.out.println(ar[i]);
}
r.close();
}
}
输出:
{"year":"2015","org":"1","sub_org":"2","sub_org_amt":"1"}
{"year":"2016","org":"2","sub_org":"3","sub_org_amt":"1"}