Converting JSON Strings to HashMaps in Java
When working with data in JSON format, converting it into a HashMap can be a useful way to store and access information. Here's how you can achieve this conversion using the org.json library.
Using org.json Library
Recursive Example
The following code provides a recursive implementation that handles nested JSON structures:
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
If you prefer, you can also use the Jackson library for JSON parsing. This approach is more concise and requires fewer steps:
import com.fasterxml.jackson.databind.ObjectMapper; Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
The above is the detailed content of How do you convert JSON strings to HashMaps in Java using org.json and Jackson libraries?. For more information, please follow other related articles on the PHP Chinese website!