一种解决方法是使用自定义的DTO(数据传输对象)。在DTO中包含基本接口和子类的属性,然后将DTO列表返回给API控制器。
以Java为例,假设有以下接口和两个子类:
public interface Animal {
String getName();
}
public class Cat implements Animal {
private String name;
private String color;
public Cat(String name, String color) {
this.name = name;
this.color = color;
}
@Override
public String getName() {
return name;
}
public String getColor() {
return color;
}
}
public class Dog implements Animal {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
定义一个DTO,它包含基本接口和子类的属性:
public class AnimalDTO {
private String name;
private String color;
private int age;
public AnimalDTO(Animal animal) {
this.name = animal.getName();
if (animal instanceof Cat) {
this.color = ((Cat) animal).getColor();
} else if (animal instanceof Dog) {
this.age = ((Dog) animal).getAge();
}
}
// getters
}
在API控制器中,将基本接口的列表转换为DTO列表:
@RestController
public class AnimalController {
@GetMapping("/animals")
public List getAnimals() {
List animals = Arrays.asList(new Cat("Lily", "White"), new Dog("Max", 2));
return animals.stream().map(AnimalDTO::new).collect(Collectors.toList());
}
}
当调用API控制器时,返回的JSON响应中将包含子类的属性:
[
{"name": "Lily", "color