Explain Codes LogoExplain Codes Logo

Convert a JSON String to a HashMap

java
json-parsing
json-object
hashmap
Nikita BarsukovbyNikita Barsukov·Oct 16, 2024
TLDR

Quickly convert a JSON String to a HashMap using Jackson's ObjectMapper:

import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; String json = "{\"key1\":\"value1\",\"key2\":2}"; // No, it's not a magic spell ObjectMapper mapper = new ObjectMapper(); // Here you command: "Hey, ObjectMapper! Make yourself useful!" Map<String, Object> result = mapper.readValue(json, Map.class); // JSON -> Map. As simple as that!

The code instantaneously transforms the JSON string into a Map with string keys and object values.

For nested JSON woes

Nested JSON structures? No worries, accurately map those pesky inner objects and arrays:

import org.json.JSONObject; import java.util.HashMap; import java.util.Map; String nestedJson = "{\"name\":\"John\", \"contact\":{\"email\":\"[email protected]\", \"phone\":\"1234567890\"}}"; JSONObject jsonObject = new JSONObject(nestedJson); Map<String, Object> result = jsonObject.toMap(); // Even the innermost values are captured.

You can resort to simpler alternatives like ObjectMapper from Jackson or Gson from Google:

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.HashMap; Gson gson = new Gson(); // Gson: your new best friend Type type = new TypeToken<HashMap<String, Object>>(){}.getType(); HashMap<String, Object> result = gson.fromJson(nestedJson, type); // Bazinga! Nested JSON -> HashMap

Deep dive with recursion

To preserve the data types in a HashMap, recursion works wonders:

private static Map<String, Object> parseJSONObject(JSONObject json) { Map<String, Object> resultMap = new HashMap<>(); // Prepare an empty basket json.keys().forEachRemaining(key -> { // For each key in json Object value = json.get(key); // Get the associated value resultMap.put(key, value instanceof JSONObject ? parseJSONObject((JSONObject) value) : value instanceof JSONArray ? parseJSONArray((JSONArray) value) : value); // Add it to the basket (recursively if necessary). }); return resultMap; // Ta-da! Returning a neatly packed basket. } private static List<Object> parseJSONArray(JSONArray array) { // A parser especially for JSON arrays List<Object> resultList = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { // For each item in the array Object item = array.get(i); resultList.add(item instanceof JSONObject ? parseJSONObject((JSONObject) item) : item instanceof JSONArray ? parseJSONArray((JSONArray) item) : item); // Add it to the list. Again, recursion is our ally. } return resultList; // Voila! A list as a result. }

Safeguarding with error handling

Sorcerer's rule: Always prepare for the worst. Add try-catch blocks to fend off those nasty IOException and JsonProcessingException:

try { Map<String, Object> result = mapper.readValue(json, Map.class); // Proceed if things look good } catch (IOException e) { e.printStackTrace(); // Oops! Something went wrong? // Handle according to your grand plan. }

JSR 353 for standardized approach

Standardization freaks, try JSR 353 for Java API for JSON Processing (JSON-P):

import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import java.io.StringReader; import java.util.Map; String json = "{\"key1\":\"value1\",\"key2\":2}"; JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject jsonObject = jsonReader.readObject(); // Ready to roll with JSON-P Map<String, Object> result = jsonObject; // JSON-P's take on JSON -> HashMap conversion

Handling arrays like a pro

ArrayList comes to the rescue when JSON arrays come knocking at the HashMap doors:

JSONArray jsonArray = new JSONArray("[\"John\", \"Jane\", \"Doe\"]"); List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getString(i)); // Adding goodies to the list. } myHashMap.put("names", list); // Your HashMap just got more charismatic!

Decoding documentation for mastery

To slay the JSON → HashMap conversion, get cozy with their respective documentation. Dive deep into practical examples and get hands-on for an enhanced understanding.