0

I have the following

public class Zoo{
  int id;
  String name;
  List<Animal> animalList;
  List<Bathroom> bathrooms;
}

public interface Animal{
  //animal has some common methods, but is mostly for naming
}

public class Cat implement Animal{
  int legs;//4
  String language;//meow
  String name;// owner
}

public class Horse implements Animal{
  String name;
  String owner;
  List<Race> races;//list of races this horse is scheduled to run
}

And I have many more types of Animals that do completely different things from each other.

Now the problem is when I try to covert a Zoo object to json, the animal blocks are there but completely empty: no data. How do I solve this problem?

conversion code

Zoo zoo = createCompleteZooObject();
Gson gson = new Gson();
String json = gson.toJson(zoo);
System.out.println(json)

Notice that I have no problem getting the list of bathrooms List<Bathroom> bathrooms as Json. Only the Animal (since it's an interface) is not showing up.

Nouvel Travay
  • 6,292
  • 13
  • 40
  • 65

1 Answers1

0

Please, checkout this answer. Gson cannot work with interface fields, because it does not knows which class it actualy should to use. Why not try to make an Animal abstract class?

Community
  • 1
  • 1
  • Thanks for replying, but changing from interface to abstract class makes no difference. The question is essentially the same: how do I get polymorphism to work with Gson. – Nouvel Travay Jan 11 '16 at 20:41
  • And I already looked at the link you provide. I cannot seem to get RuntimeTypeAdapterFactory even after using `compile 'com.google.code.gson:gson:2.5'` – Nouvel Travay Jan 11 '16 at 20:48