解析具有动态密钥的JSONObject

时间:2015-04-20 09:56:05

标签: android json

我跟随JSON作为来自我的服务器的响应。起初,我想,这是无效的JSON,但在验证之后,似乎是正确的:

JOSN: {
    "category": {
        "1": "World",
        "2": "Politics",
        "3": "Economy",
        "4": "Sports",
        "5": "Cricket",
        "6": "General",
        "7": "Business",
        "8": "Services",
        "9": "Law & Order",
        "10": "Entertainment"
    }
}

验证:JSON Validatiion

如果它是JSONArray,我会用SO的解决方案解析它:How to parse a JSON without key in android?

但是我如何解析我在这里的JSON?

任何帮助表示感谢。

4 个答案:

答案 0 :(得分:15)

  

但是我如何解析我在这里的JSON?

如果category JSONObject中的键是动态的,那么使用JSONObject.keys()获取Iterator以获取值:

JSONObject mainJSONObj=new JSONObject(<json_string>);
// get category JSONObject from mainJSONObj
JSONObject categoryJSONObj=mainJSONObj.getJSONObject("category");

// get all keys from categoryJSONObj

Iterator<String> iterator = categoryJSONObj.keys();
  while (iterator.hasNext()) {
    String key = iterator.next();
    Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key);
  }

答案 1 :(得分:5)

尝试将gson反序列化与此类的对象一起用作序列化输出类:

class MyClass {
    @SerializedName("category")
    private Map<String, String> categories;

    public Map<String, String> getCategories() {
       return categories;
    }

    public void setCategories(Map<String, String> categories) {
        this.categories = categories;
    }
}

答案 2 :(得分:1)

如果我是你,而且我确定键是一系列以1 开头的数字,我会执行以下操作:

Map<Integer, String> results = new Hashtable<>();

    try {
        //The response is your JSON as a string
        JSONObject obj = new JSONObject(response);
        JSONObject categories = obj.getJSONObject("categories");

        int counter = 1;
        //Breakable infinite loop, will be broken when you try to get non existing item
        while(true){
            results.put(counter, categories.getString(counter+""));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
//Return the map that contain the results
 return results;

或使用Iterator作为以下example

Map<Integer, String> results = new Hashtable<>();

    try {
        //The response is your JSON as a string
        JSONObject obj = new JSONObject(response);
        JSONObject categories = obj.getJSONObject("categories");

        Iterator<String> iter = categories.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            results.put(key, categories.getString(key+""));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //Return the map that contain the results
    return results;

您还可以创建ArrayList<String>并为其添加值,而不是将其添加到HashTable

答案 3 :(得分:0)

试试这段代码

JSONObject obj = result.getJSONObject("category");
    Iterator keys = obj.keys();

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

        String value= obj.getString(dynamicKey);
    }

有关详情,请查看此link。可能这会对你有所帮助。