How to Convert JSON String to Map in Java using Jackson


Suppose we’re working with a JSON string that we want to deserialize into a map.

String json = "{\"id\":1,\"breed\":\"corgi\"}";

We want to convert this JSON string into a map with a String key and generic Object value (Map<String, Object>).

We can use the jackson-core and jackson-mapper libraries to achieve this.

Using Jackson to deserialize JSON to map

Let’s see how we can use ObjectMapper to read the JSON string.

ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> map = mapper.readValue(json, Map.class);

We could also specify a different class for the key and value (instead of String.class and Object.class). We use Object for the value in this scenario since we have both Integer and String types.

Using Jackson to serialize map into JSON

Similarly, we can use ObjectMapper to write a map into a JSON string.

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map)