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 !!
how to get the value of “age” only.Thanks
how to do it for the json array?
[{“age”:29,”name”:”shan”}, {“age”:30,”name”:”more”}]
How do you handle the special characters like ” in the json Mapping
Use character escaping using backslash.
Amazing article, so it’s clear so many bad habits on me when coding or the thinking…thank you so much for offer this and hope more from U.
hi lokesh,,
tell me the best way to handle the jvm memory issues.