- Given an array of user defined objects , we need to convert array of POJOs to JSON String.
- Also, we will convert the JSON String to array of POJOs.
- We will use the Google gson library for serialization and deserialization process.
- We will create Person class and we will perform the following operations with Person class
- Convert Person[] array to JSON string
- Convert the JSON string to Person[] array
GSON Maven dependency:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.5</version> </dependency>
Program – Convert/ Serialize array of objects to/from json (Gson & example)
1.) Person Class:
- Person class containing firstName, lastName, age etc.
- We have overloaded toString method to print person information.
package org.learn.gson;
public class Person {
public String firstName;
public String lastName;
public int age;
public String contact;
public Person(String firstName, String lastName,
int age, String contact) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.contact = contact;
}
public String toString() {
return "[" + firstName + " " + lastName +
" " + age + " " +contact +"]";
}
}
2.) JSONArrayConverter Class:
JSONArrayConverter is responsible for performing following operations.
- Convert Person[] array to JSON string
- Convert the JSON string to Person[] array
package org.learn.gson;
import java.util.Arrays;
import java.util.stream.Stream;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JSONArrayConverter
{
public static void main( String[] args )
{
Gson objGson = new GsonBuilder().setPrettyPrinting().create();
Person[] personList = Stream.of(
new Person("Mike", "harvey", 34, "001894536"),
new Person("Nick", "young", 75, "005425676"),
new Person("Jack", "slater", 21 ,"009654153"),
new Person("gary", "hudson", 55,"00564536"))
.toArray(Person[]::new);
//Array to JSON
String mapToJson = objGson.toJson(personList);
System.out.println("1. Person array to JSON conversion is : \n");
System.out.println(mapToJson);
//JSON to Array
Person[] arrayPerson = objGson.fromJson(mapToJson, Person[].class);
System.out.println("2. JSON to Array of persons conversion is :\n");
Arrays.stream(arrayPerson).forEach(System.out::println);
}
}
Download code – Serialize array of objects to/from JSON (GSON)
Output – convert array of objects to/from json (Gson & example)
1. Person array to JSON conversion is :
[
{
"firstName": "Mike",
"lastName": "harvey",
"age": 34,
"contact": "001894536"
},
{
"firstName": "Nick",
"lastName": "young",
"age": 75,
"contact": "005425676"
},
{
"firstName": "Jack",
"lastName": "slater",
"age": 21,
"contact": "009654153"
},
{
"firstName": "gary",
"lastName": "hudson",
"age": 55,
"contact": "00564536"
}
]
2. JSON to Array of persons conversion is :
[Mike harvey 34 001894536]
[Nick young 75 005425676]
[Jack slater 21 009654153]
[gary hudson 55 00564536]