Categories
Java Java-Json binding by Jackson

Java Map to JSON

In this example we will see transformation of Java Map to JSON and vice-versa. JSON provides capability to map the primitive data types as well as standard collection objects. Jackson provides easy APIs to achieve it.

We use maven, so here is POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>custom.jackson</groupId>
  <artifactId>learning</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>learning</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
	      <groupId>junit</groupId>
	      <artifactId>junit</artifactId>
	      <version>3.8.1</version>
	      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.12.3</version>
   </dependency>
   <dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.12.3</version>
	</dependency>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-annotations</artifactId>
	    <version>2.12.3</version>
	</dependency>
  </dependencies>
</project>


We have simple class with Main method to demonstrate, App2.java. It contains map of country as key, capital city as value.

package custom.jackson.learning;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App2 {

	public static void main(String[] args) throws Exception{
		
		//Map of country with Capital city
		Map map = new HashMap();
		map.put("India", "Delhi");
		map.put("Japan", "Tokyo");
		map.put("China", "Beijing");
		map.put("USA", "New York");
		map.put("Russia", "Moscow");

		//Convert Map to JSON
		ObjectMapper mapper = new ObjectMapper();
		String jsonResult = mapper.writerWithDefaultPrettyPrinter()
		  .writeValueAsString(map);
		System.out.println("Convert Map to JSON ::"+jsonResult);
		
		 
		Map map2 = mapper.readValue(jsonResult, Map.class);
		System.out.println("Convert JSON to Map ::"+map2); 
		
		

	}

}

Output :

As seen above, in first step Map is converted to JSON string. In second step we are converting JSON String into Java.util.Map object.

Leave a comment

Design a site like this with WordPress.com
Get started