java - 如何迭代json字符串

标签 java json

我有一个 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/

相关文章:

javascript - 使用 javascript 从输入文本字段中检索 json 对象值

java - 通过按下按钮将图像添加到框架

java - 如何在Spring MVC测试框架中测试配置静态资源

java - ConstraintViolationException : NOT NULL when using Spring, HSQL 和 Hibernate

java - 如何用JAVA发回JSON?

c# - 为 WebSocket 响应选择缓冲区大小

java - shape.intersects 函数 - 行为

java - Spring批处理中的网格大小

java - 使用 JSON 升级到 Spring MVC 4.1 发生 HTTP 406 错误

json - 我应该在 Solr 中使用什么字段类型、分词器和查询来搜索存储 JSON 的字段?