others-How to serialize and deserialize java ArrayList with gson?

1. Purpose

In this post, I would demo how to do java ArrayList and JSON conversion by using gson, we would use java template method which has a generic type to do this job.

2. Environment

  • java 1.8+
  • gson 2.x

3. The solution

3.1 The old way

When we want to serialize a List object to json and parse json string to a List, we can do this job using TypeToken.

Suppose we have a MyCar object:

class MyCar {
    String manu;
    Date bornDate;
    String type;
    String description;

    public static MyCar newCar(String manu, Date borndate, String type, String desc) {
        MyCar myCar = new MyCar();
        myCar.manu = manu;
        myCar.bornDate = borndate;
        myCar.type = type;
        myCar.description = desc;
        return myCar;
    }

    public String getManu() {
        return manu;
    }

    public void setManu(String manu) {
        this.manu = manu;
    }

    public Date getBornDate() {
        return bornDate;
    }

    public void setBornDate(Date bornDate) {
        this.bornDate = bornDate;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

If we want to use gson, we should add dependency as follows:

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

Then we can define a TypeToken like this:

private static final Type mycarTypeToken = new TypeToken<ArrayList<EmailTarget>>() {}.getType();

What is a TypeToken?

public class TypeToken<T> extends Object. Represents a generic type T . Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime

Then we can parse the JSON to List as follows:

public static List<MyCar> getList(String json) {
        if(json==null) return null;
        return gson.fromJson(json, mycarTypeToken);
}

We can convert List to JSON as follows:

public static String getJson(List myCarList) {
        if(myCarList==null) return null;
        return gson.toJson(myCarList,mycarTypeToken);
}

3.2 The java template method way

We can also do this job more generally by using java template method, which has a <T> to represent any type that would be used in the conversion.

Here is the code:

Convert from List to JSON:

public static <T> String getSomeJsonString(List<T> someList) {
        if(someList==null) return null;
        Type theListType = new TypeToken<ArrayList<T>>() {}.getType();
        return gson.toJson(someList, theListType);
}

Convert from JSON to List:

public static final <T> List<T> getListFromJson(Class<T[]> theClass, String json) {
        T[] jsonToObject = new Gson().fromJson(json, theClass);
        return Arrays.asList(jsonToObject);
}

Then we can test the code as follows:

    public static void main(String[] args) {
        List<MyCar> cars = new ArrayList<>();
        cars.add(MyCar.newCar("honda",new Date(),"suv","haha ha"));
        cars.add(MyCar.newCar("audi",new Date(),"cross","askdfjla"));
        String json = getSomeJsonString(cars);
        System.out.println(json);
        List<MyCar> cars2 = getSomeList(json);
        System.out.println("got cars:"+cars2.size());
    }

Run the above code, We get this:

[{"manu":"honda","bornDate":"Aug 26, 2021 2:59:22 PM","type":"suv","description":"haha ha"},{"manu":"audi","bornDate":"Aug 26, 2021 2:59:22 PM","type":"cross","description":"askdfjla"}]
got cars:2

Process finished with exit code 0

4. Summary

In this post, I demonstrated how to serialize and deserialize List from and to JSON string by using gson and java template method.