简体   繁体   English

Java 8 JSON-simple - 我如何阅读子项?

[英]Java 8 JSON-simple - How can i read a subitem?

I have a Problem in Java, specially in work with the JSON-simple Library. 我有一个Java问题,特别是在使用JSON-simple Library时。 I have found here a code, they does work in the level of a parent node from a json-file but at my case, i read a json-file with childs under the parents. 我在这里找到了一个代码,它们确实在json文件的父节点级别工作但在我的情况下,我在父节点下读了一个带有子节点的json文件。

Link to the code: How to read json file into java with simple JSON library 链接到代码: 如何使用简单的JSON库将json文件读入java

In DB-Language: i have a database with some tables. 在DB语言中:我有一个包含一些表的数据库。 Now, i can only read "select * from table" but i want to read the column (or attribute) from it. 现在,我只能读取“select * from table”但我想从中读取列(或属性)。


The Structure (raw data json): 结构(原始数据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"
}
}

The Code: 编码:

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;
}

You have 1 "root" JSONObject , containing 3 nodes, each an instance of JSONObject . 你有1个“root” JSONObject ,包含3个节点,每个节点都是JSONObject一个实例。 These 3 nodes each contains 2 nested nodes. 这3个节点每个包含2个嵌套节点。 json-simple will treat these as strings, if you traverse through the structure. 如果遍历结构,json-simple会将这些视为字符串。

To print out the contents of your parents, you'd have to do something similar to: 要打印出父母的内容,你必须做类似的事情:

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"));

This would ouput 这将输出

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

If you want to be able to iterate over all the childs, you should define each parent as a JSONArray , and each child as a JSONObject 如果您希望能够遍历所有子节点,则应将每个父节点定义为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"}
    ]
}

If your structure would always follow this sample: 1 root object with x-amount parent array objects, each with y-amount child objects, where the child objects never have any nested nodes, one way to iterate over all of them would be: 如果您的结构始终遵循此示例:1个具有x-amount父数组对象的根对象,每个对象具有y-amount子对象,其中子对象永远不会有任何嵌套节点,迭代所有这些对象的一种方法是:

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());
    }
}

The above (with the parent node names) would output: 以上(使用父节点名称)将输出:

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]

When calling #keySet() and #values() on the child node, it will return as a Set and a Collection, respectively. 在子节点上调用#keySet()#values()时,它将分别作为Set和Collection返回。 When using #toString() on these, the output will be printed enclosed in brackets ( [keys/values] ). 在这些上使用#toString()时,输出将打印在括号内( [keys/values] )。 You can of course just ask for an array, and then the first entry, to get the lonely key/value: child.keySet().toArray()[0] and child.values().toArray()[0] . 你当然可以要求一个数组,然后是第一个条目,以获得孤独的键/值: child.keySet().toArray()[0]child.values().toArray()[0] This won't of course work, if you have nested nodes inside your child nodes - in such case, it would only print the first key/value for the particular node. 这当然不工作,如果你有嵌套的子节点的节点-在这种情况下,这将只打印了特定节点的第一个键/值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM