- Jackson Java convert between JSON and Map
- 2. Dependencies
- 3.1. Serialization – convert Map to a JSON
- 3.2.1. Configure TypeReference for Map deserialization
- 4.1. Serialization – convert Map to a JSON
- 4.2. Deserialize to Map from JSON
- 3.2.1. Configure TypeReference for Map deserialization
- 3.2.2. Configure TypeFactory for Map deserialization
- 5. Conclusion
- Convert JSON to Hashmap using Jackson
- Setup
- JSON to Map
- Java map to json
- Convert JSON String to Java Map with Jackson
- Convert JSON String to Java Map
- Free eBook: Git Essentials
Jackson Java convert between JSON and Map
In this article, we will learn to convert between JSON and Map in Java using Jackson library.
To learn more about Jackson, refer to our articles.
By encoding your Java object as a JSON string, you can transfer the Java Map object over a network or store it in a database or a file.
Serialization is converting your Java object in your application to the JSON format, whereas deserialization converts the JSON back into the original Java object.
ObjectMapper class of Jackson helps you with the serialization and deserialization process in Java. Let’s understand how to configure your Jackson to convert between Map and JSON.
2. Dependencies
To get started, you must add the Jackson library as a dependency in your project.
com.fasterxml.jackson.core jackson-databind 2.13.0
This ObjectMapper class is available in the Jackson databind project.
The com.fasterxml.jackson.core.databind library dependency pulls in all other required dependencies into your project:
3. Jackson convert between JSON and Map
Let’s see serialization and deserialization between JSON and Map.
3.1. Serialization – convert Map to a JSON
There is no special configuration required to convert Map to JSON. You can simply use the ObjectMapper class to convert the Map to JSON.
For example, the below test method contains a Map of users and their corresponding age .
@Test void serializeMap_String_String() throws JsonProcessingException < Mapmap = new HashMap<>(); map.put("John", "15"); map.put("Mike", "25"); map.put("Jackson", "45"); ObjectMapper mapper = new ObjectMapper(); String jsonResult = mapper.writeValueAsString(map); System.out.println(jsonResult); >
If you run the above code, the ObjectMapper converts the Map to JSON and prints the following result:
3.2. Deserialization – convert JSON to Map
You can deserialize the JSON with an array of objects to Map by using the ObjectMapper’s readValue method and passing Map.class as a parameter. However, IDE throws unchecked assignment Map to Map.
@Test void dserializeMap_String_String() throws JsonProcessingException < String mapStr = ""; ObjectMapper mapper = new ObjectMapper(); Map map = mapper.readValue(mapStr, Map.class); for (Map.Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value has-inline-color has-vivid-red-color">Type safety: The expression of type Map needs unchecked conversion to conform to Map3.2.1. Configure TypeReference for Map deserialization
You can prevent the unchecked assignment error by using the
TypeReference
, a class of Jackson library that allows to provide the type information to Jackson. Therefore, Jackson resolves to the provided type.@Test void dserializeMap_String_String() throws JsonProcessingException < String mapStr = ""; ObjectMapper mapper = new ObjectMapper(); TypeReferencetypeRef = new TypeReference () <>; Map map = mapper.readValue(mapStr, typeRef); for (Map.Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value wp-block-heading">3.2.2. Configure TypeFactory for Map deserialization Alternatively, you can use the overloaded
readValue
function that accepts the JavaType as input:public T readValue(String content, JavaType valueType) throws JsonProcessingException, JsonMappingExceptionThe JavaType is the base class that contains type information for deserializer. To create a JavaType , you first need to get the configured and readily available TypeFactory instance from the ObjectMapper object.
TypeFactory typeFactory = mapper.getTypeFactory();You can create the MapType (subclass of JavaType ) to deserialize the JSON array of objects as a Map object.
typeFactory.constructMapType(HashMap.class, String.class, String.class)@Test void dserializeMap_String_String_TypeFactory() throws JsonProcessingException < String mapStr = ""; ObjectMapper mapper = new ObjectMapper(); TypeFactory typeFactory = mapper.getTypeFactory(); Map map = mapper.readValue(mapStr, typeFactory.constructMapType(HashMap.class, String.class, String.class)); for (Map.Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value wp-block-heading">4. Jackson convert between JSON and MapLet’s see serialization and deserialization between JSON and Map.
4.1. Serialization – convert Map to a JSON
Here, no special configuration is required to convert Map to JSON. You can simply use the
ObjectMapper
class to convert the Map to JSON.For example, the below test method contains an
Map
of students sorted by their rank.@Test void serializeMap_String_Object() throws JsonProcessingException < Mapmap = new HashMap<>(); Student student = new Student("John", "Smith"); map.put("First", student); Student jack = new Student("Mike", "Jack"); map.put("Second", jack); ObjectMapper mapper = new ObjectMapper(); String jsonResult = mapper.writeValueAsString(map); System.out.println(jsonResult); /* prints ,"First":> */ >4.2. Deserialize to Map from JSON
You can deserialize the JSON with an array of objects to Map by using the ObjectMapper'sreadValue method and passing Map.class as a parameter. However, IDE throws unchecked assignment Map to Map.
@Test void dserializeMap_String_Object() throws JsonProcessingException < String mapStr = ",\"First\":>"; ObjectMapper mapper = new ObjectMapper(); Map map = mapper.readValue(mapStr, Map.class); for (Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Key = Second, Value = Key = First, Value =
Though the above code works fine and provides the expected result, the IDE would show the following warning
Type safety: The expression of type Map needs unchecked conversion to conform to Map
3.2.1. Configure TypeReference for Map deserialization
You can prevent the unchecked assignment error by using the TypeReference , a class of Jackson library that allows providing the type information to Jackson. Therefore, Jackson resolves to the provided type.
@Test void dserializeMap_String_Object_TypeRef() throws JsonProcessingException < String mapStr = ",\"First\":>"; ObjectMapper mapper = new ObjectMapper(); TypeReference> typeRef = new TypeReference>() <>; Map map = mapper.readValue(mapStr, typeRef); for (Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Key = Second, Value = Key = First, Value =
3.2.2. Configure TypeFactory for Map deserialization
Alternatively, you can use the overloaded readValue function that accepts the JavaType as input:
public T readValue(String content, JavaType valueType) throws JsonProcessingException, JsonMappingExceptionThe JavaType is the base class that contains type information for deserializer. To create a JavaType , you first need to get the configured and readily available TypeFactory instance from the ObjectMapper object.
TypeFactory typeFactory = mapper.getTypeFactory();You can create the MapType (subclass of JavaType ) to deserialize the JSON array of objects as a Map object.
typeFactory.constructMapType(HashMap.class, String.class, Student.class)@Test void dserializeMap_String_Object_TypeFactory() throws JsonProcessingException < String mapStr = ",\"First\":>"; ObjectMapper mapper = new ObjectMapper(); TypeFactory typeFactory = mapper.getTypeFactory(); Map map = mapper.readValue(mapStr, typeFactory.constructMapType(HashMap.class, String.class, Student.class)); for (Map.Entry entry : map.entrySet()) < System.out.println("Key = " + entry.getKey() + ", Value EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Key = Second, Value = Key = First, Value =
5. Conclusion
To sum up, we have learned to serialize or deserialize maps using the Jackson library.
Convert JSON to Hashmap using Jackson
In the set up section we borrowed json snippet from json.org example that will be used in the each of the snippets below.
Setup
String sampleJson = "ID":"SGML", "SortAs":"SGML", "GlossTerm":"Standard Generalized Markup Language", "Acronym":"SGML", "Abbrev":"ISO 8879:1986" >
JSON to Map
First initializing jackson's object mapper is the heart of jackson as it provides functionality for converting between Java objects and matching JSON constructs. Next we will read the sameJson value from above and pass a TypeReference into an overloaded readValue method. TypeReference is a class used used for obtaining full generics type information and an additional constructor mapper.readValue(src, Map.class) but you get a nasty check style error. Finally we will assert that the map has the following keys using hamcrest.
@Test public void json_to_map() throws JsonParseException, JsonMappingException, IOException MapString, Object> map = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(sampleJson, new TypeReferenceHashMapString, Object>>() >); // OR map = mapper.readValue(sampleJson, HashMap.class); logger.info(sampleJson); assertThat(map.keySet(), hasItems("ID", "SortAs", "GlossTerm", "Acronym", "Abbrev")); >
Java map to json
Flipping the snippet above around we will create a map object that resembles the same json value above. Instead of reading the value we will call writeValueAsString which will return the map as json in a java string.
@Test public void java_map_to_json() throws JsonProcessingException // initialize map MapString, Object> map = new LinkedHashMap<>(); map.put("ID", "SGML"); map.put("SortAs", "SGML"); map.put("GlossTerm", "Standard Generalized Markup Language"); map.put("Acronym", "SGML"); map.put("Abbrev", "ISO 8879:1986"); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(map); logger.info(json); assertEquals(json, sampleJson); >
Convert JSON to Hashmap using Jackson posted by Justin Musgrove on 10 August 2014
Tagged: java and java-json
Convert JSON String to Java Map with Jackson
In this tutorial, we'll be taking a look at how to convert a JSON String into a Java Map using Jackson, an extremely popular data-binding library for Java.
Specifically, we'll be working with this JSON object:
< "Task 1" : "In_Progress", "Task 2" : "Done", "Task 3" : "Planned" >
Since we're working with an external library, let's add the required dependency. If you're using Maven, you can add it to your project with:
dependency> groupId>com.fasterxml.jackson.core groupId> artifactId>jackson-databind artifactId> version>2.11.3 version> dependency>
Or if you're using Gradle, you can add:
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.11.3'
Convert JSON String to Java Map
For our task status labels, let's define an Enum. We'll have a Map pair, though, you can go with any type here, really:
Naturally, Jackson's key class is the ObjectMapper class - the main API for object-related data-binding of the library.
Much like you'd map JSON values to other types, to convert JSON contents into a Java Map, you'll use the readValue() method of the ObjectMapper instance, which deserializes it into the provided class reference:
String json = " + "\"Task 1\" : \"In_Progress\",\n" + "\"Task 2\" : \"Done\",\n" + "\"Task 3\" : \"Planned\"\n" + ">"; // ObjectMapper instantiation ObjectMapper objectMapper = new ObjectMapper(); // Deserialization into a Map Map result = objectMapper.readValue(json, HashMap.class); // Printing the results System.out.println(result.entrySet());
We've chucked the json contents into the readValue() method, and since it contains JSON that can be deserialized into a Map, given the key-value pairings, told Jackson to deserialize into a HashMap . Running this code results in:
[Task 2=Done, Task 1=In_Progress, Task 3=Planned]
Now, since HashMap s do not preserve the order of insertion, you might want to use a LinkedHashMap instead, if the order of insertion is important to you:
Map result = objectMapper.readValue(json, LinkedHashMap.class);
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
[Task 1=In_Progress, Task 2=Done, Task 3=Planned]
An alternative to specifying the JavaType directly would be to use the TypeReference class from Jackson:
Map result = objectMapper.readValue(json, new TypeReference()<>);
Now, printing this map will also result in:
[Task 1=In_Progress, Task 2=Done, Task 3=Planned]
Both of these construct an object by calling the exact same deserialization process. So the only difference between these two calls is whether you're making a static ( JavaType ) or dynamic ( TypeReference ) reference to the type.