others-How to serialize enum type with gson?

1. Purpose

In this post, I would demo how to do serialization for enum types with gson in java applications.

2. Environment

  • java 1.6+
  • gson 2.8.5+

3. The solution

3.1 Add gson dependency

We can add dependency with maven as follows:

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

or with gradle:

dependencies {
  implementation 'com.google.code.gson:gson:2.8.7'
}

What is gson?

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

The goals of gson:

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

###

3.2 The code example

Suppose we have a domain object, which type is ‘Car’, Here is the diagram of the Car type:

image-20210811103022922

You can see that there is a type field in the Car , which is a enum type of java. Here is the definition:

class Car {
    private String name;
    private CarType carType;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public CarType getCarType() {
        return carType;
    }

    public void setCarType(CarType carType) {
        this.carType = carType;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", carType=" + carType +
                '}';
    }
}

enum CarType {
    SUV,
    SEDAN,
    HATCHBACK,
    CROSS
}

Now , we want to serialize the Car to json and then deserialize the Car from json. Here is the demo:

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

    public static void main(String[] args) {
        List<Car> cars = getCars();
        Gson gson = new Gson();
        String carsJson = gson.toJson(cars,carListType);
        System.out.println(carsJson);
        List<Car> cars2 = gson.fromJson(carsJson,carListType);
        for(Car car:cars2) {
            System.out.println(car);
        }
    }

    private static List<Car> getCars() {
        List<Car> cars = new ArrayList<>();
        Car c = new Car();
        c.setName("fit");
        c.setCarType(CarType.HATCHBACK);
        cars.add(c);

        c = new Car();
        c.setName("benz");
        c.setCarType(CarType.SEDAN);
        cars.add(c);
        return cars;
    }

Let’s run the code:

[{"name":"fit","carType":"HATCHBACK"},{"name":"benz","carType":"SEDAN"}]
Car{name='fit', carType=HATCHBACK}
Car{name='benz', carType=SEDAN}

3.3 The whole code

Here is the whole code example:

public class Gson1 {
    private static final Type carListType = new TypeToken<ArrayList<Car>>() {
    }.getType();

    public static void main(String[] args) {
        List<Car> cars = getCars();
        Gson gson = new Gson();
        String carsJson = gson.toJson(cars,carListType);
        System.out.println(carsJson);
        List<Car> cars2 = gson.fromJson(carsJson,carListType);
        for(Car car:cars2) {
            System.out.println(car);
        }
    }

    private static List<Car> getCars() {
        List<Car> cars = new ArrayList<>();
        Car c = new Car();
        c.setName("fit");
        c.setCarType(CarType.HATCHBACK);
        cars.add(c);

        c = new Car();
        c.setName("benz");
        c.setCarType(CarType.SEDAN);
        cars.add(c);
        return cars;
    }
}

class Car {
    private String name;
    private CarType carType;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public CarType getCarType() {
        return carType;
    }

    public void setCarType(CarType carType) {
        this.carType = carType;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", carType=" + carType +
                '}';
    }
}

enum CarType {
    SUV,
    SEDAN,
    HATCHBACK,
    CROSS
}

4. Summary

In this post, I demonstrated how to serialize and deserialize the class with enum fields with gson.