Convert JSON String of Array to/from List of Java Objects (Gson)

Maven dependency of Google Gson JSON Library

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Convert JSON Array to/from List of Java Objects (Gson):

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

class Person {
    private String name;
    private int age;

    public String getName() {return name;}
    public int getAge() {return age;}
}

public class JsonParserGson {

    // Constructors, getters, setters...

    public static void main(String[] args) {
        String jsonArrayString = "[" +
                "{\"name\":\"Honey\",\"age\":30}," +
                "{\"name\":\"Mike\",\"age\":25}" +
                "]";

        // Create Gson instance
        Gson gson = new Gson();

        // Define the type of the collection
        Type personListType = new TypeToken<List>() {}.getType();

        // Convert JSON Array to List of Java Objects
        List personList = gson.fromJson(jsonArrayString, personListType);

        System.out.println("JSON String to List of Person Object:");

        // Access the List of Java Objects
        for (Person person : personList) {
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
        }

        // Convert List to JSON Array
        String jsonPerson = gson.toJson(personList);

        // Print JSON Array
        System.out.println("List of Person List to String:");
        System.out.println(jsonPerson);
    }
}

Output:

JSON String to List of Person Object:
Name: Honey
Age: 30
Name: Mike
Age: 25
List of Person List to String:
[{"name":"Honey","age":30},{"name":"Mike","age":25}]
Scroll to Top