访问嵌套结果中的动态 JSON 键
在 JSON 数据中,键可以是动态的,这意味着它们因对象而异。这在访问特定值时可能会带来挑战,尤其是在嵌套结构中。
要处理嵌套结果中的动态 JSON 键,您可以利用 JSONObject 类中的 keys() 方法。此方法返回一个迭代器,允许您迭代 JSON 对象中的可用键。
考虑以下 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" } ] }
访问“question_mark”字段的内容对于“search_result”数组中的每个对象,您可以使用以下代码:
for (JSONObject searchResult : searchResults) { JSONObject questionMark = searchResult.getJSONObject("question_mark"); Iterator<String> keys = questionMark.keys(); while (keys.hasNext()) { String currentDynamicKey = keys.next(); // Get the value of the dynamic key JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // Do something here with the value... } }
此代码迭代“question_mark”字段中的可用键并检索与每个键关联的值。然后,您可以使用这些值进行进一步处理或显示。
以上是如何访问嵌套结果中的动态 JSON 键?的详细内容。更多信息请关注PHP中文网其他相关文章!