Parsing JSONObject having dynamic key

后端 未结 4 1563
感情败类
感情败类 2021-01-03 07:34

I have following JSON as response from my server. At first, I thought, it was invalid JSON but after validating it, it seems to be correct:

JOSN: {
    \"cat         


        
4条回答
  •  一生所求
    2021-01-03 08:14

    If I were you and I'm sure that the keys are a sequence of numbers starting with 1, I would do the following:

    Map 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;
    

    Or using Iterator as the following example :

    Map results = new Hashtable<>();
    
        try {
            //The response is your JSON as a string
            JSONObject obj = new JSONObject(response);
            JSONObject categories = obj.getJSONObject("categories");
    
            Iterator 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;
    

    You can also create an ArrayList and add the values to it instead of adding them to a HashTable

提交回复
热议问题