请问如何在嵌套的JSON结果中解析动态JSON密钥?

如何在嵌套的JSON结果中解析动态JSON密钥?

我有以下格式的JSON结果,JSON Lint将其显示为“有效响应”。

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

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

//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"
            },

我的问题标题“动态密钥”可能是错误的,但我不知道在这一点上什么是这个问题的更好的名称。

任何帮助将不胜感激!


慕码人8056858
浏览 286回答 3
3回答

小怪兽爱吃肉

使用JSONObject keys()获取密钥,然后迭代每个密钥以获取动态值。代码大致如下:&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;searchResult&nbsp;refers&nbsp;to&nbsp;the&nbsp;current&nbsp;element&nbsp;in&nbsp;the&nbsp;array&nbsp;"search_result" &nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;questionMark&nbsp;=&nbsp;searchResult.getJSONObject("question_mark"); &nbsp;&nbsp;&nbsp;&nbsp;Iterator&nbsp;keys&nbsp;=&nbsp;questionMark.keys(); &nbsp;&nbsp;&nbsp;&nbsp;while(keys.hasNext())&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;loop&nbsp;to&nbsp;get&nbsp;the&nbsp;dynamic&nbsp;key &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;currentDynamicKey&nbsp;=&nbsp;(String)keys.next(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;get&nbsp;the&nbsp;value&nbsp;of&nbsp;the&nbsp;dynamic&nbsp;key &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSONObject&nbsp;currentDynamicValue&nbsp;=&nbsp;questionMark.getJSONObject(currentDynamicKey); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;do&nbsp;something&nbsp;here&nbsp;with&nbsp;the&nbsp;value... &nbsp;&nbsp;&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java