如何遍历Java中的json对象 [英] how to iterate through json objects in java

查看:679
本文介绍了如何遍历Java中的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历json文件并获取所需的详细信息 这是我的json

I am trying to iterate through my json file and get required details here is my json

{
"000": {
    "component": "c",
    "determinantType": "dt",
    "determinant": "d",
    "header": "h",
    "determinantvalue": "null"
},
"001": {
    "component": "t",
    "determinantType": "i",
    "determinant":"ld",
    "header": "D",
    "determinantvalue": "null"
},
"002": {
    "component": "x",
    "determinantType": "id",
    "determinant": "pld",
    "header": "P",
    "determinantValue": "null"
}}

我的Java代码

FileReader file = new FileReader("test.json");
Object obj = parser.parse(file);
System.out.println(obj);
JSONObject jsonObject = (JSONObject) obj;            
JSONArray msg = (JSONArray) jsonObject.get(key);          
Iterator<String> iterator = msg.iterator();         
while (iterator.hasNext()) {
System.out.println(iterator.next());            
String component = (String) jsonObject.get("component");           
System.out.println("component: " + component);           

正如您在代码中看到的那样,我正在导入json文件并尝试从中获取下一个元素并打印组件,我还应该同时打印标头,行列式和行列式值 谢谢

As you can see in the code I am importing my json file and trying to get next elements and printing components out of it , I should also print header,determinant and determinant value as well Thank you

推荐答案

您没有数组-您拥有名称为"000"等的 properties .数组如下所示:

You don't have an array - you have properties with names of "000" etc. An array would look like this:

"array": [ {
    "foo": "bar1",
    "baz": "qux1"
  }, {
    "foo": "bar2",
    "baz": "qux2"
  }
]

请注意[ ... ]-这表示JSON数组.

Note the [ ... ] - that's what indicates a JSON array.

您可以使用 keys() :

You can iterate through the properties of a JSONObject using keys():

// Unfortunately keys() just returns a raw Iterator...
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
    Object key = keys.next();
    JSONObject value = jsonObject.getJSONObject((String) key);
    String component = value.getString("component");
    System.out.println(component);
}

或者:

@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
    String key = keys.next();
    JSONObject value = jsonObject.getJSONObject(key);
    String component = value.getString("component");
    System.out.println(component);
}

这篇关于如何遍历Java中的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆