小编典典

使用JSON Java检索嵌套数组值

json

我正在努力从格式如下的JSON文件中检索一些值:

{
  "search": {
    "entry": [
      {
        "found": "identity=9454532,l=big,ton=grand,k=molvi",
        "attribute": [
          {
            "name": "firstname",
            "value": [
              "Lucas"
            ]
          },
          {
            "name": "lastname",
            "value": [
              "Brandon"
            ]
          }
        ]
      }
    ],
    "return": {
      "code": 0,
      "message": "Success",
      "count": 1
    }
  }
}

我尝试了不同的方法(json,gson,jayway-
JsonPath),但是我无法从“属性”数组中获取值,只能从第一个数组中获取值。我不知道如何指定“属性”是一个JSONArray而不是一个JSONObject或如何为其设置正确的路径。这是我正在玩的最后一个代码,当它找到一个数组时停止:

public void String nameObtain (String email) throws IOException{

String link = "http://jsonfile/" + email;

    JSONObject json = readJsonFromUrl(link);        
    JSONObject rootObject = json.getJSONObject("search");
    JSONArray firstArray = rootObject.getJSONArray("entry");

for (int i = 0, size = firstArray.length(); i < size; i++) {
    JSONObject objectInArray = firstArray.getJSONObject(i);

    String[] elementNames = JSONObject.getNames(objectInArray);
    System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
    for (String elementName : elementNames) {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
    }

}

}

我想做的就是获得卢卡斯或布兰登的价值。任何帮助都感激不尽!


阅读 271

收藏
2020-07-27

共1个答案

小编典典

使用的库:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

检查以下代码并逐步解析

    JSONObject search = (JSONObject) jsonObject.get("search");//1
    JSONArray entry = (JSONArray) search.get("entry");//2
    for (int i = 0; i < entry.size(); i++) {
        JSONObject jsonObject1 = (JSONObject) entry.get(i);//3
        JSONArray jsonarray1 = (JSONArray) jsonObject1.get("attribute");//4
        for (int j = 0; j < jsonarray1.size(); j++) {
            System.out.println(((JSONObject) jsonarray1.get(j)).get(
                    "value").toString());//5

        }

    }

它将逐步给出所提到的值:

1){“ entry”:[{“ found”:“ identity = 9454532,l = big,ton = grand,k = molvi”,“
attribute”:[{“ name”:“ firstname”,“ value”:[ “ Lucas”]},{“ name”:“姓氏”,“
value”:[“ Brandon”]}}}}],“返回”:{“ code”:0,“ count”:1,“ message”: “成功”}}

2)[{“ found”:“ identity = 9454532,l = big,ton = grand,k = molvi”,“
attribute”:[{“ name”:“ firstname”,“ value”:[“ Lucas”]} ,{“ name”:“
lastname”,“ value”:[“ Brandon”]}]}]]

3){“ found”:“ identity = 9454532,l = big,ton = grand,k = molvi”,“
attribute”:[{“ name”:“ firstname”,“ value”:[“ Lucas”]}, {“ name”:“
lastname”,“ value”:[“ Brandon”]}]}

4)[{“ name”:“ firstname”,“ value”:[“ Lucas”]},{“ name”:“ lastname”,“
value”:[“ Brandon”]}]

5)[“ Lucas”]和[“ Brandon”]

因此,基本上,您必须分别照顾JSONObject和JSONArray并进行相应的解析。

2020-07-27