首页  >  文章  >  Java  >  如何访问嵌套 JSON 结果中的动态键?

如何访问嵌套 JSON 结果中的动态键?

DDD
DDD原创
2024-11-08 00:54:03852浏览

How to Access Dynamic Keys in Nested JSON Results?

解析嵌套 JSON 结果中的动态 JSON 键

问题:

如何访问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"
            }
       ]
}

解决方案:

要访问嵌套 JSON 结果中的动态键,请使用 JSONObject 类的 keys() 方法。此方法返回一个迭代器,可用于迭代对象中的键。获得密钥后,您可以使用 getJSONObject(key) 方法检索相应的值。

以下示例展示了如何解析示例 JSON 中的动态密钥:

JSONObject searchResult = ...;  // Assuming searchResult is a JSONObject

JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while (keys.hasNext()) {
    String currentDynamicKey = (String) keys.next();
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

    // Do something with the dynamic key and value...
}

此代码迭代 Question_mark 对象中的键并检索相应的值。然后您可以使用这些值来访问您需要的数据。

以上是如何访问嵌套 JSON 结果中的动态键?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn