如何在spring @RestController

时间:2018-03-02 12:36:30

标签: java spring-mvc spring-restcontroller jackson2

有没有办法在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;
    }

1 个答案:

答案 0 :(得分:0)

以这种方式对单个请求的不同响应类型使用ResponseEntity。

    @RequestMapping(value="/test",method = RequestMethod.GET)
    public ResponseEntity<Object> testRequest() { 
         ........
        return new ResponseEntity(resultObject, responseStatus).

    }