I came across some weird behavior in GSON.
If I have the following class structure:
public interface Animal {
public void nothing();
}
public class Cat implements Animal {
private String name;
public Cat(String name) {
super();
this.name = name;
}
public Cat(){}
@Override
public void nothing() {
// TODO Auto-generated method stub
};
}
public class Dog implements Animal {
private String name;
public Dog(String name) {
super();
this.name = name;
}
public Dog(){}
@Override
public void nothing() {
// TODO Auto-generated method stub
};
}
I can do this:
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Cat("Betty"));
animals.add(new Dog("Fred"));
System.out.println(gson.toJson(animals));
and get this output:
[{"name":"Betty"},{"name":"Fred"}]
However, if I put animals
into a containing class:
public class Container {
List<Animal> animals = new ArrayList<Animal>();
public void addAnimal(Animal a){
animals.add(a);
}
}
and call:
Container container = new Container();
container.addAnimal(new Cat("betty"));
System.out.println(gson.toJson(container));
I get:
{"animals":[{}]}
It looks like GSON can serialize a list of an interface List<Interface>
when that list is by itself, but when the list is contained in another class, GSON has problems.
Any idea what I'm doing wrong?
As a side note, I can correctly deserialize a json string into the correct type using a custom deserializer. It's the serializing that is giving me issues.
Thanks