Deserialize a List<T> object with Gson in java?

Deserialize a List<T> object with Gson in java?

To deserialize a JSON array into a List<T> object using Gson in Java, you'll need to specify the type of the list using Gson's TypeToken. Here's how you can do it:

Suppose you have a class Person that represents the objects you want to deserialize:

import java.util.List; public class Person { private String name; private int age; // Constructors, getters, setters, etc. } 

And you have a JSON array representing a list of Person objects:

[ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 35} ] 

Here's how you can deserialize this JSON array into a List<Person>:

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class DeserializeListExample { public static void main(String[] args) { String json = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30},{\"name\":\"Charlie\",\"age\":35}]"; // Create a Gson instance Gson gson = new Gson(); // Define the type of the list using TypeToken TypeToken<List<Person>> listTypeToken = new TypeToken<List<Person>>() {}; // Deserialize the JSON array into a List<Person> List<Person> personList = gson.fromJson(json, listTypeToken.getType()); // Now you can work with the List<Person> for (Person person : personList) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge()); } } } 

In this code:

  1. We define a JSON string json containing an array of Person objects.

  2. We create a Gson instance gson.

  3. We define the type of the list using TypeToken with List<Person> as the generic type. This allows Gson to correctly deserialize the JSON array into a List<Person>.

  4. We use gson.fromJson(json, listTypeToken.getType()) to deserialize the JSON array into a List<Person>.

  5. Finally, we iterate through the list and access the Person objects.

Make sure to import the necessary Gson classes (com.google.gson.Gson and com.google.gson.reflect.TypeToken). This approach allows you to deserialize JSON arrays into a list of objects of the specified type.


More Tags

poco zkteco wpf-positioning firebase-dynamic-links firefox-addon-webextensions amqp identification swift3 vb.net-to-c# refresh

More Java Questions

More Housing Building Calculators

More Chemical reactions Calculators

More Tax and Salary Calculators

More Electrochemistry Calculators