Jackson – Marshal and Unmarshal Java Maps

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.


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.


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 !!


Notify of
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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode