I have a generic class containing a field of type T, Gson serializes this field as an empty object. I have provided the code below to demonstrate this problem. Reading JSON backwards seems fine (as long as you supply the correct type token).
import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GsonIssue { static class AbstractThing { private String fieldA = "valueA"; public String getFieldA() { return fieldA; } public void setFieldA(String fieldA) { this.fieldA = fieldA; } @Override public String toString() { return "AbstractThing [fieldA=" + fieldA + "]"; } } static class Thing extends AbstractThing { private String fieldB = "valueB"; @Override public String toString() { return "Thing [fieldB=" + fieldB + ", fieldA=" + getFieldA() + "]"; } } static class Wrapper<T extends AbstractThing> { private T abstractThing; private String standardField = "standard value"; public Wrapper(T abstractThing) { this.abstractThing = abstractThing; } @Override public String toString() { return "Wrapper [abstractThing=" + abstractThing + ", standardField=" + standardField + "]"; } } public static void main(String[] args) { Wrapper<Thing> wrapper = new Wrapper<Thing>(new Thing()); Gson gson = new Gson(); String json = gson.toJson(wrapper); System.out.println(json);
source share