[Jackson API Examples] - How to Convert Java List 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 List 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 List Object to/from JSON String using Jackson?(Serialize and Deserialize)

MainApp.java

package com.javainspires;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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 {
		// convert java list object to json string
		// create a list object
		List<String> sampleList = new ArrayList<String>();
		// add elements to list
		sampleList.add("C");
		sampleList.add("C++");
		sampleList.add("Java");
		sampleList.add("Python");
		sampleList.add("GOLang");

		// create object mapper
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		// convert list to string
		String listJson = mapper.writeValueAsString(sampleList);
		System.out.println("Java List objeect to JSON\n");
		System.out.println(listJson);

		// convert back to list object

		List<String> list1 = mapper.readValue(listJson.getBytes(), List.class);
		System.out.println("\nJSON String to Java List Object\n");
		// print this list
		list1.forEach(System.out::println);

	}
}



Output:

Java List objeect to JSON

[ "C", "C++", "Java", "Python", "GOLang" ]

JSON String to Java List Object

C
C++
Java
Python
GOLang

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