Convert JSONObject to Map Convert JSONObject to Map json json

Convert JSONObject to Map


use Jackson (https://github.com/FasterXML/jackson) from http://json.org/

HashMap<String,Object> result =       new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);


You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);


This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {        Map<String, Object> map = new HashMap<String, Object>();        Iterator<String> keys = jsonobj.keys();        while(keys.hasNext()) {            String key = keys.next();            Object value = jsonobj.get(key);            if (value instanceof JSONArray) {                value = toList((JSONArray) value);            } else if (value instanceof JSONObject) {                value = toMap((JSONObject) value);            }               map.put(key, value);        }   return map;    }    public static List<Object> toList(JSONArray array) throws JSONException {        List<Object> list = new ArrayList<Object>();        for(int i = 0; i < array.length(); i++) {            Object value = array.get(i);            if (value instanceof JSONArray) {                value = toList((JSONArray) value);            }            else if (value instanceof JSONObject) {                value = toMap((JSONObject) value);            }            list.add(value);        }   return list;}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java