gpt4 book ai didi

java - 使用 JSON Java 检索嵌套数组值

转载 作者:行者123 更新时间:2023-11-30 06:52:39 25 4
gpt4 key购买 nike

我正在努力从格式如下的 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);
}

}

}

我想做的是获取 Lucas 或 Brandon 的值。任何帮助都感激不尽!

最佳答案

使用的库:

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":"lastname","value":["Brandon"]}]}],"return":{"code":0,"count":1,"message":"Success"}}

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"] and ["Brandon"]

所以基本上您必须分别处理 JSONObject 和 JSONArray 并进行相应的解析。

关于java - 使用 JSON Java 检索嵌套数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com