【问题标题】:Java 8 JSON-simple - How can i read a subitem?Java 8 JSON-simple - 我如何读取子项?
【发布时间】:2025-12-23 11:35:11
【问题描述】:

我有一个 Java 问题,特别是在使用 JSON 简单库时。我在这里找到了一个代码,它们确实在 json 文件的父节点级别工作,但在我的情况下,我读取了一个 json 文件,其父节点下有子节点。

代码链接:How to read json file into java with simple JSON library

在 DB 语言中:我有一个包含一些表的数据库。现在,我只能读取“从表中选择 *”,但我想从中读取列(或属性)。


结构(原始数据 json):

{
"PARENT1":
{
"child_attr1":"0.00","child_attr2":"0.30"
},
"PARENT2":
{
"child_attr1":"0.10","child_attr2":"0.12"
},
"PARENT3":
{
"child_attr1":"0.03","child_attr2":"0.45"
}
}

代码:

public static HttpResponse http(String url, String body) {    
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost request = new HttpPost(url);
        StringEntity params = new StringEntity(body);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse result = httpClient.execute(request);

        String json_content = EntityUtils.toString(result.getEntity(), "UTF-8");
        //System.out.println(json_content);

        try {
            JSONParser parser = new JSONParser();
            Object resultObject = parser.parse(json_content);

            if (resultObject instanceof JSONArray) {
                JSONArray array=(JSONArray)resultObject;
                for (Object object : array) {
                    JSONObject obj =(JSONObject)object;
                    System.out.println(obj.get("Parent"));
                    System.out.println(obj.get("Child"));
                    //System.out.println("case1"); 
                }

            } else if (resultObject instanceof JSONObject) {
                JSONObject obj =(JSONObject)resultObject;
                System.out.println(obj.get("PARENT2"));
                //System.out.println("case2"); 
                //THIS KNOT WORKS BUT IT GIVES ME ALL VALUES OF THE ATTRIBUTES 


            }
        } catch (Exception e) {
          // TODO: handle exception
          e.printStackTrace();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return null;
}

【问题讨论】:

  • 我懂你的英语。我不明白你的问题,因为你提到了一些表和一些代码,但你没有包括你如何使用这些代码、这些表的定义以及你在尝试时遇到的错误
  • 我编辑了我的问题。我希望这会更好,感谢您的帮助!
  • 又是什么问题?你也可以提供 JSON 结构吗?
  • 你的问题还是比较模糊。您能否向我们提供 JSON 数据的结构?并告诉我们您要读取哪些节点。从表中读取属性是什么意思?这是您的 JSON 问题的一部分,还是一个单独的问题(在这种情况下,您应该为其创建一个单独的问题)。

标签: java json json-simple


【解决方案1】:

您有 1 个“根”JSONObject,包含 3 个节点,每个节点都是 JSONObject 的实例。这 3 个节点每个都包含 2 个嵌套节点。如果您遍历结构,json-simple 会将这些视为字符串。

要打印出你父母的内容,你必须做类似的事情:

JSONParser parser = new JSONParser();

JSONObject parents = (JSONObject) parser.parse(new FileReader("filename"));

JSONObject parent1 = (JSONObject) parents.get("PARENT1");
JSONObject parent2 = (JSONObject) parents.get("PARENT2");
JSONObject parent3 = (JSONObject) parents.get("PARENT3");

System.out.println("Parent 1");
System.out.println("\tChild 1: " + parent1.get("child_attr1"));
System.out.println("\tChild 2: " + parent1.get("child_attr2"));

System.out.println("Parent 2");
System.out.println("\tChild 1: " + parent2.get("child_attr1"));
System.out.println("\tChild 2: " + parent2.get("child_attr2"));

System.out.println("Parent 3");
System.out.println("\tChild 1: " + parent3.get("child_attr1"));
System.out.println("\tChild 2: " + parent3.get("child_attr2"));

这将输出

Parent 1
    Child 1: 0.00
    Child 2: 0.30
Parent 2
    Child 1: 0.10
    Child 2: 0.12
Parent 3
    Child 1: 0.03
    Child 2: 0.45

如果您希望能够遍历所有子代,则应将每个父代定义为JSONArray,将每个子代定义为JSONObject

{
    "PARENT1": [
        {"child_attr1": "0.00"},
        {"child_attr2": "0.30"}
    ],
    "PARENT2": [
        {"child_attr1": "0.10"},
        {"child_attr2": "0.12"}
    ],
    "PARENT3": [
        {"child_attr1": "0.14"},
        {"child_attr2": "0.45"}
    ]
}

如果您的结构始终遵循此示例: 1 个具有 x 数量父数组对象的根对象,每个具有 y 数量的子对象,其中子对象从不具有任何嵌套节点,一种遍历所有对象的方法是是:

Iterator<?> i = parents.keySet().iterator();
// Alternative, if you don't need the name of the key of the parent node:
// Iterator<?> i = parents.values().iterator();
while(i.hasNext()) {
    String parentKey = (String) i.next();
    JSONArray p = (JSONArray) parents.get(parentKey);
    System.out.println(parentKey);

    // If you don't need the name of the parent key node, 
    // replace the above with:
    // JSONArray p = (JSONArray) i.next();
    // Remember to use the alternative iterator-definition above as well

    for(Object o : p) {
        JSONObject child = (JSONObject) o;
        System.out.println("\t" + child.keySet() + ": " + child.values());
    }
}

上面(带有父节点名称)将输出:

PARENT1
    [child_attr1]: [0.00]
    [child_attr2]: [0.30]
PARENT3
    [child_attr1]: [0.14]
    [child_attr2]: [0.25]
PARENT2
    [child_attr1]: [0.10]
    [child_attr2]: [0.12]

在子节点上调用#keySet()#values()时,会分别返回一个Set和一个Collection。在这些上使用#toString() 时,输出将打印在括号中([keys/values])。您当然可以只要求一个数组,然后是第一个条目,以获取单独的键/值:child.keySet().toArray()[0]child.values().toArray()[0]。如果您的子节点内部有嵌套节点,这当然行不通——在这种情况下,它只会打印特定节点的第一个键/值。

【讨论】:

  • 真的,谢谢你,eli!这是一个完整的答案! :)