Convert a JSON String to a HashMap Convert a JSON String to a HashMap java java

Convert a JSON String to a HashMap


I wrote this code some days back by recursion.

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {    Map<String, Object> retMap = new HashMap<String, Object>();        if(json != JSONObject.NULL) {        retMap = toMap(json);    }    return retMap;}public static Map<String, Object> toMap(JSONObject object) throws JSONException {    Map<String, Object> map = new HashMap<String, Object>();    Iterator<String> keysItr = object.keys();    while(keysItr.hasNext()) {        String key = keysItr.next();        Object value = object.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;}

Using Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {};Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, typeRef);


Using Gson, you can do the following:

Map<String, Object> retMap = new Gson().fromJson(    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType());


Hope this will work, try this:

import com.fasterxml.jackson.databind.ObjectMapper;Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str, your JSON String

As Simple as this, if you want emailid,

String emailIds = response.get("email id").toString();