Parse JSON object with string and value only
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); }
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;