0

我正在尝试遍历 json 文件并找到特定 json 对象的值。这是我的示例 json:

{
  "diagram":[
             {"size":{"width":30,"height":20},"color":"blue","id":1}, 
             {"color":"red","id":2},
             {"size:{"height":30}", "id":3}
            ]
}

我想要做的是遍历文件并找到“id”元素。

我使用下面的代码将 JsonFile 转换为 JsonObject 并获取“图表”对象的值

JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("D:/test.json"));
JSONObject jsonObj = (JSONObject) obj;
for(Iterator iterator = jsonObj.keySet().iterator(); iterator.hasNext();) {
      String diagramKey = (String) iterator.next();
      jsonArray.put(jsonObj.get(diagramKey));
}

使用上面的代码,我能够获得图表对象的值,并将其放入 jsonArray

当我尝试打印数组对象时,我得到的输出为

[[
  {"size":{"width":30,"height":20},"color":"blue","id":1}, 
  {"color":"red","id":2},
  {"size:{"height":30}", "id":3}
]]

并且 jsonArray 长度为 1。

如何遍历上面的 jsonArray 并找到每个单独元素的 id

4

2 回答 2

1
Verify your JSON too and check below code. 

public class MyTest {

    public static void main(String[] args) throws JSONException {
        String str = "{\r\n" + 
                "   \"diagram\": [{\r\n" + 
                "           \"size\": {\r\n" + 
                "               \"width\": 30,\r\n" + 
                "               \"height\": 20\r\n" + 
                "           },\r\n" + 
                "           \"color\": \"blue\",\r\n" + 
                "           \"id\": 1\r\n" + 
                "       },\r\n" + 
                "       {\r\n" + 
                "           \"color\": \"red\",\r\n" + 
                "           \"id\": 2\r\n" + 
                "       },\r\n" + 
                "       {\r\n" + 
                "           \"size\": {\r\n" + 
                "               \"height\": 30\r\n" + 
                "           },\r\n" + 
                "           \"id\": 3\r\n" + 
                "       }\r\n" + 
                "   ]\r\n" + 
                "}";

        JSONObject jo = new JSONObject(str);
        final JSONArray geodata = jo.getJSONArray("diagram");
        int arrLength = geodata.length();
        for(int i = 0; i< arrLength;i++) {
            jo  = geodata.getJSONObject(i);
            System.out.println(jo.get("id"));
        }
    }
}
于 2019-05-16T09:54:28.617 回答
0

您的 json 格式错误。您始终可以使用在线工具验证您的 json 格式

正确的json格式

{  
   "diagram":[  
      {  
         "size":{  
            "width":30,
            "height":20
         },
         "color":"blue",
         "id":1
      },
      {  
         "color":"red",
         "id":2
      },
      {  
         "size":{  
            "height":30
         },
         "id":3
      }
   ]
}
于 2019-05-16T09:57:32.363 回答