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

新手上路,请多包涵

我有以下格式的 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"
            }
       ]
}

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

任何帮助将不胜感激!

原文由 Sagar Hatekar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 596
2 个回答

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

大致代码如下所示:


// 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...
}

原文由 momo 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种可能性是使用 Gson (注意,我在这里使用 lombok 来生成 getter/setter、toString 等):

 package so7304002;

import java.util.List;
import java.util.Map;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JsonDemo {
    @Data
    private static class MyMap {
        private int count;

        @SerializedName("more_description")
        private String moreDescription;

        private int seq;
    }

    @Data
    private static class Product {
        private String product;

        private int id;

        @SerializedName("question_mark")
        private Map<String, MyMap> questionMark;
    }

    @Data
    private static class MyObject {
        private String status;

        @SerializedName("search_result")
        private List<Product> searchResult;
    }

    private static final String INPUT = ""; // your JSON

    public static void main(final String[] arg) {
        final MyObject fromJson = new Gson().fromJson(INPUT,
            new TypeToken<MyObject>(){}.getType());
        final List<Product> searchResult = fromJson.getSearchResult();
        for (final Product p : searchResult) {
            System.out.println("product: " + p.getProduct()
                + "\n" + p.getQuestionMark()+ "\n");
        }
    }
}

输出:

 product: abc
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2),
 8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)}

product: XYZ
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5),
 845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6),
 12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4),
 257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)}

原文由 user180100 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题