Parse JSON object with string and value only

103,973

Solution 1

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Solution 2

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;
Share:
103,973
Edy Cu
Author by

Edy Cu

Updated on December 11, 2020

Comments

  • Edy Cu
    Edy Cu over 3 years

    I have problem when trying to parse with minimum value to map in Android.

    There some sample JSON format with more information ex:

    [{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
    

    This that example most common to use and easy to use just use getString("id") or getValue("name").

    But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:

    {"1":"sql", "2":"android", "3":"mvc"}
    

    Thank

  • Z2VvZ3Vp
    Z2VvZ3Vp almost 10 years
    Probably because they're asking about a json object not json array.
  • Buhake Sindi
    Buhake Sindi almost 10 years
    @PixMach the String the OP provided is a JSON array. It starts with a [ and ends with a ].
  • 8bitjunkie
    8bitjunkie over 7 years
    What's the import for JSONObject?
  • damjad
    damjad almost 7 years
    @8bitjunkie, It's org.json:json