如何使用Gson将Java接口转换为Json
我有以下几点如何使用Gson将Java接口转换为Json,java,android,json,gson,Java,Android,Json,Gson,我有以下几点 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
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
}
请注意,我可以将浴室列表
list bathrooms
作为Json获取。只有动物(因为它是一个界面)没有出现。请结帐。Gson无法处理接口字段,因为它不知道实际应该使用哪个类。为什么不尝试创建一个动物抽象类?请向我们展示执行此转换的代码。感谢您的回复,但从接口更改为抽象类没有任何区别。问题基本上是一样的:如何让多态性与Gson一起工作。我已经看过了您提供的链接。即使在使用compile'com.google.code.gson:gson:2.5'
Zoo zoo = createCompleteZooObject();
Gson gson = new Gson();
String json = gson.toJson(zoo);
System.out.println(json)