morristech
6/24/2019 - 2:35 PM

Java Google Json (Gson) Serializing Generics http://www.studytrails.com/java/json/java-google-json-serializing-classes-with-generic-type.jsp

public class Animal<T> {
 
    public T animal;
 
    public void setAnimal(T animal) {
        this.animal = animal;
    }
 
    public T get() {
        return animal;
    }
 
} 
public class Dog {
    private String name;
 
    public Dog(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
} 
import java.lang.reflect.Type;
 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
public class GenericTypesExample8 {
    public static void main(String[] args) {
        // create an animal class that is of type dog.
        Animal<Dog> animal = new Animal<Dog>();
        // Create a Dog instance
        Dog dog = new Dog("I am a dog");
 
        animal.setAnimal(dog);
        Gson gson = new Gson();
        // Define a Type that is an Animal of type dog.
        Type animalType = new TypeToken<Animal<Dog>>() {
        }.getType();
 
        // we first convert the animal object to a json and then read the json
        // back. However we define the json to be of Animal type
        String json = gson.toJson(animal, animalType);
        System.out.println(json);
        Animal animal1 = gson.fromJson(json, Animal.class);
        System.out.println(animal1.get().getClass()); // prints class
                                                        // com.google.gson.internal.LinkedTreeMap
 
        System.out.println();
 
        // In contrast to above where we read the json back using the Animal
        // type, here we read the json back as the custom animalType Type. This
        // gives Gson an idea of what
        // the generic type should be.
        json = gson.toJson(animal);
        System.out.println(json);
        Animal animal2 = gson.fromJson(json, animalType);
        System.out.println(animal2.get().getClass());
        // prints class com.studytrails.json.gson.Dog
 
    }
} 
{"animal":{"name":"I am a dog"}}
class com.google.gson.internal.LinkedTreeMap

{"animal":{"name":"I am a dog"}}
class Dog
#!/usr/bin/env bash
javac -cp .:gson-2.6.2.jar GenericTypesExample8.java && java -cp .:gson-2.6.2.jar GenericTypesExample8