是否有任何方法可以在spring @RestController中使用泛型类型作为结果参数?
我有这门课:
public class Response<T> {
private final T data;
private final String error;
...
}
当我尝试使用它作为结果类型时,我收到了一个错误
@RequestMapping(value = "/ping", method = {GET, POST})
public Response<String> ping() {
这是一个例外:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:259)
这个检查
this.objectMapper.canSerialize(clazz, causeRef)
在AbstractJackson2HttpMessageConverter
为我的班级返回false
。
我该如何解决这个问题?
编辑:我已经这样修复了:
public class Response<T> {
private T data;
private String error;
@JsonIgnore
@JsonTypeInfo(
use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.PROPERTY
)
private Class<T> type;
...
@JsonIgnore
public Class<T> getType() {
return type;
}
以这种方式将ResponseEntity用于单个请求的不同响应类型。
@RequestMapping(value="/test",method = RequestMethod.GET)
public ResponseEntity<Object> testRequest() {
........
return new ResponseEntity(resultObject, responseStatus).
}