[Jackson API Examples] - How to Convert Java Map Object to/from JSON String using Jackson?(Serialize and De-serialize)

#JavaInspires

Hi Guys,

Welcome to Java Inspires.

In this post, we will see how to serialize and de-serialize java Map (HashMap) object using Jackson api.

Here, we are using ObjectMapper class from Jackson library and writeValueAsString method to convert serialize and readValue method to deserialize.



How to Convert Java Map Object to/from JSON String using Jackson?(Serialize and Deserialize)

MainApp.java


package com.javainspires;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author #JavaInspires
 *
 */
public class MainApp {

	public static void main(String[] args) throws IOException {

		// create a Map object
		Map<String, Object> sampleMap = new HashMap<>();
		sampleMap.put("name","Elon Musk");
		sampleMap.put("age", 45);
		sampleMap.put("doj", new Date());
		sampleMap.put("role", "Developer");

		// create object mapper class object
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		// convert map object to json string using this mapper
		String jsonStr = mapper.writeValueAsString(sampleMap);

		System.out.println("\nJava Map Object To JSON\n");
		// print json string
		System.out.println(jsonStr);

		// now convert this json string to java map object
		// using object mapper

		Map<String, Object> map1 = mapper.readValue(jsonStr.getBytes(), Map.class);

		System.out.println("\nJSON String to Java Map Object\n");
		// print this list
		map1.entrySet().forEach(System.out::println);

	}
}





Output:


Java Map Object To JSON

{
  "role" : "Developer",
  "name" : "Elon Musk",
  "age" : 45,
  "doj" : 1623251901457
}

JSON String to Java Map Object

role=Developer
name=Elon Musk
age=45
doj=1623251901457


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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javainspires</groupId>
	<artifactId>jackson-examples</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.12.2</version>
		</dependency>

	</dependencies>
</project>





Post a Comment

Previous Post Next Post