Home >Java >javaTutorial >How to Convert a JSON String to a HashMap in Java?
Converting JSON String to a HashMap with Java
In Java, parsing JSON data and storing it in a HashMap can be achieved using various techniques. Here's how you can do it using the org.json library:
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException { Map<String, Object> retMap = new HashMap<>(); 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<>(); 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<>(); 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; }
To use this method, instantiate a JSONObject object from your JSON String, then pass it as an argument to the jsonToMap method. It will recursively parse the JSON structure and convert it into a HashMap.
Alternatively, you can use the Jackson library for a more concise solution:
import com.fasterxml.jackson.databind.ObjectMapper; Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Simply replace jsonStr with your actual JSON String.
The above is the detailed content of How to Convert a JSON String to a HashMap in Java?. For more information, please follow other related articles on the PHP Chinese website!