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

时间:2018-04-02 16:04:03

标签: java json json-simple

我在Java中遇到问题,特别是在使用JSON-simple Library时。我在这里找到了一个代码,它们在json文件的父节点级别工作但在我的情况下,我在父母的下面读了一个带有子节点的json文件。

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

在DB-Language中:我有一个包含一些表的数据库。现在,我只能阅读" select * from table"但我想从中读取列(或属性)。

结构(原始数据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;
}

1 个答案:

答案 0 :(得分:1)

您有1个“root”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-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());
    }
}

以上(使用父节点名称)将输出:

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]。如果您的子节点内嵌有节点 ,那么这当然不会起作用 - 在这种情况下,它只会打印特定节点的第一个键/值。