我试图遍历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并获取“ diagram”对象的值
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
答案 0 :(得分:0)
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"));
}
}
}
答案 1 :(得分:0)
您的json格式错误。 您始终可以在线使用工具来验证json格式
正确的json格式
{
"diagram":[
{
"size":{
"width":30,
"height":20
},
"color":"blue",
"id":1
},
{
"color":"red",
"id":2
},
{
"size":{
"height":30
},
"id":3
}
]
}