Site icon

Convert Array of Objects to / from JSON – Jackson ObjectMapper

Given an array of user defined objects, we would like to convert array of object to JSON and JSON to array of objects. We will use the Jackson’s ObjectMapper to achieve the conversion. We will create Person class and we will perform the following operations with Person class

Jackson ObjectMapper Maven Dependencies 

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId> 
	<artifactId>jackson-databind</artifactId>
	<version>2.7.1</version> 
</dependency>

Program to convert array of POJOs to/from JSON (Objectmapper)

1.) Person Class:

public class Person {
	public String firstName;
	public String lastName;
	public int age;
	public Person() {		
	}
	public Person(String firstName, String lastName,
				int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	public String toString() {
	    return "[" + firstName + " " + lastName +
		       " " + age +"]";
	}
}

2.) JSONArrayConverter Class:

  1. Given an array of Person objects.
  2. Convert array of Person objects to JSON String using Jackson ObjectMapper.
  3. Convert JSON String to array of person objects.
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;

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

public class JSONArrayConverter 
{
    public static void main( String[] args ) throws IOException
    {
    	ObjectMapper objectMapper = new ObjectMapper();
    	//Set pretty printing of json
    	objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    	//Define map which will be converted to JSON
    	Person[] personList = Stream.of(
				new Person("Mike", "harvey", 34),
			  	new Person("Nick", "young", 75),
				new Person("Jack", "slater", 21 ),
				new Person("gary", "hudson", 55))
				.toArray(Person[]::new);
    	
    	//1. Convert Array to JSON
    	String arrayToJson = objectMapper.writeValueAsString(personList);
    	System.out.println("1. Convert Array to JSON :");
    	System.out.println(arrayToJson);
    	
    	//2. JSON to Array
    	//Define Custom Type reference for map type
    	Person[] jsonToArray = objectMapper.readValue(arrayToJson, Person[].class);
    	System.out.println("\n2. Convert JSON to Array :");
    	
    	//Print array output using Java 8
    	Arrays.stream(jsonToArray).forEach(System.out::println);
    }
}

Download Code – Jackson ObjectMapper Array to JSON

Output : Convert array of objects to/from JSON (Jackson ObjectMapper)

1. Convert Array to JSON :
[ {
  "firstName" : "Mike",
  "lastName" : "harvey",
  "age" : 34
}, {
  "firstName" : "Nick",
  "lastName" : "young",
  "age" : 75
}, {
  "firstName" : "Jack",
  "lastName" : "slater",
  "age" : 21
}, {
  "firstName" : "gary",
  "lastName" : "hudson",
  "age" : 55
} ]

2. Convert JSON to Array :
[Mike harvey 34]
[Nick young 75]
[Jack slater 21]
[gary hudson 55]
Exit mobile version