Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Gson将Java接口转换为Json_Java_Android_Json_Gson - Fatal编程技术网

如何使用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)