我有两个类 A
和 B
正在实现一个接口(interface)。
public class A implements MyInterface {
// Class A stuff
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class B implements MyInterface {
//Class B stuff
private MyCustomClass myCustomclass;
public String getName() {
this.myCustomclass.getName();
}
}
public interface MyInterface {
public String getName();
}
我想使用一个 Controller 方法,它可以在 A 和 B 上工作,具体取决于前端发送的对象。因此,当我尝试使用接口(interface)时,Spring 提示找不到合适的消息转换器。
@RequestMapping(value = "/mymethod", method = RequestMethod.POST) public String updateRecord(@RequestBody MyInterface myInterface, HttpServletResponse response) { //Do stuff }
最佳答案
Jackson 可以确定使用哪个实现序列化为 JSON,但无法确定使用哪个实现反序列化 JSON。对于序列化,它需要做的就是调用 getClass() 并为该类型构建一个序列化程序。但是在反序列化时(目前)没有这样的类型信息。您应该使用 Jackson 注释 @JsonTypeInfo
和 @JsonSubTypes
来实现多态 json。
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = A.class, name = "A"),
@JsonSubTypes.Type(value = B.class, name = "B")})
public interface MyInterface {
}
那么请求体myInterface
一定是,
{type:'A', name:'我的名字'}
或 {type:'B', myCustomclass:{....}}
引用这三个:
Spring MVC @RequestBody into an Interface instead of a class
https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization
Spring @RequestBody containing a list of different types (but same interface)
关于java - 在 Spring Controller 方法参数中使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965921/