gpt4 book ai didi

java - 如何解析嵌套 JSON 结果中的动态 JSON 键?

转载 作者:IT老高 更新时间:2023-10-28 12:45:41 25 4
gpt4 key购买 nike

我有一个 JSON 结果,格式如下 JSON Lint将此显示为“有效响应”。

我的问题是:我如何访问“question_mark”的内容,因为“141”、“8911”等都是动态值?

我用于访问“产品”值的示例代码。

//Consider I have the first <code>JSONObject</code> of the "search_result" array and 
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//<code>product<code> now contains "abc".

JSON:

{
"status": "OK",
"search_result": [

{
"product": "abc",
"id": "1132",
"question_mark": {
"141": {
"count": "141",
"more_description": "this is abc",
"seq": "2"
},
"8911": {
"count": "8911",
"more_desc": "this is cup",
"seq": "1"
}
},
"name": "some name",
"description": "This is some product"
},
{
"product": "XYZ",
"id": "1129",
"question_mark": {
"379": {
"count": "379",
"more_desc": "this is xyz",
"seq": "5"
},
"845": {
"count": "845",
"more_desc": "this is table",
"seq": "6"
},
"12383": {
"count": "12383",
"more_desc": "Jumbo",
"seq": "4"
},
"257258": {
"count": "257258",
"more_desc": "large",
"seq": "1"
}
},
"name": "some other name",
"description": "this is some other product"
}
]
}

我的问题标题“动态键”可能是错误的,但我目前不知道这个问题的更好名称是什么。

任何帮助将不胜感激!

最佳答案

使用 JSONObject keys()获取 key ,然后迭代每个 key 以获取动态值。

代码大致如下:


// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();

// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

// do something here with the value...
}

关于java - 如何解析嵌套 JSON 结果中的动态 JSON 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7304002/

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