我有一个 JSON 字符串数组,例如:
[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]
我希望能够迭代这个数组,并希望在 Java 中获取它的 id、字段、值
使用下面的代码我得到了一个异常 “json 对象必须以 {”开头
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
JSONObject obj = new JSONObject(rules);
System.out.println("====obj===="+obj);
// boolean error = obj.getBoolean("error");
String id = obj.getString("id");
System.out.println("===id is===: "+id);
} catch (JSONException e){
e.printStackTrace();
}
最佳答案
您应该从字符串创建一个 JSONArray
,然后迭代该数组。将您的代码修改为
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
// create the json array from String rules
JSONArray jsonRules = new JSONArray(rules);
// iterate over the rules
for (int i=0; i<jsonRules.length();i++){
JSONObject obj = jsonRules.get(i);
System.out.println("====obj===="+obj);
String id = obj.getString("id");
System.out.println("===id is===: "+id);
}
} catch (JSONException e){
e.printStackTrace();
}
关于java - 如何迭代json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597950/