Jackson – Marshal and Unmarshal Java Maps

Learn to convert JSON to Map and convert a Map to JSON string using Jackson 2. Given example uses Jackson ObjectMapper for conversions.

json editor

In this Jackson tutorial, we will learn to convert JSON to Java Map objects and vice-versa.

1. Maven

Include Jackson dependency in your application project. Do not forget to check for the latest dependency at Maven site.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
</dependency>

2. Converting Map to JSON

Java program to convert Map to JSON is as follows. We are using HashMap here.

HashMap<String, String> hashmap = new HashMap<String, String>();

hashmap.put("id", "1");
hashmap.put("firstName", "Lokesh");
hashmap.put("lastName", "Gupta");

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

Program Output.

{"id":"1","lastName":"Gupta","firstName":"Lokesh"}

3. Converting JSON to Map

Java program to convert JSON to Map is as follows. we are using TypeReference which is used to describe the type of our destination class type.

String json = "{\"id\":\"1\",\"name\":\"Lokesh Gupta\",\"age\":34,\"location\":\"India\"}";

ObjectMapper mapper = new ObjectMapper();
     
HashMap<String, String> map 
  = mapper.readValue(json, new TypeReference<Map<String, String>>(){});

Program Output.

{id=1, name=Lokesh Gupta, age=34, location=India}

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.