【问题标题】:Spring 3 with ResponseBody ignoring @JsonTypeInfo带有 ResponseBody 的 Spring 3 忽略 @JsonTypeInfo
【发布时间】:2015-07-24 08:23:24
【问题描述】:

我无法使用定义类的附加属性让 spring 返回我的对象​​的序列化。

我的课程是:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.PROPERTY, property="ObjectType")
@JsonSubTypes({
    @JsonSubTypes.Type(value=LiteStudy.class, name="LiteStudy")
})
public class Entity {
...
}


@JsonTypeName("LiteStudy")
@JsonSubTypes({
        @JsonSubTypes.Type(value=Study.class, name="Study")
})
public class LiteStudy extends Entity {
...
}


@JsonTypeName("Study")
public class Study extends LiteStudy{
...
}

在我的单元测试中,一个 Study 实例被正确序列化,具有该类的额外属性:

{"ObjectType":"Study",
...
}

使用简单:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(studyJSON,study.getClass());

但是,在我的 Spring Rest webservice 模块中,研究是在没有“ObjectType”属性的情况下序列化的。

控制器看起来像这样(简化):

@ResponseBody
public RestResponse<Study> getStudyById(@PathVariable("studyIdentifier")    String studyIdentifier) throws DAOException {

    return getStudyRestResponse(studyIdentifier);
}

编辑:添加 RestResponse(简化)

public class RestResponse<Content> {

private Content content;
private String message;
private Exception err;

public Content getContent() {
    return content;
}

public void setContent(Content content) {
    this.content = content;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public Exception getErr() {
    return err;
}

public void setErr(Exception err) {
    this.err = err;
}

知道为什么 spring 似乎忽略了 @JsonType 注释吗?

【问题讨论】:

  • 你试过搜索stackoverflow吗?也许其中一些可以帮助您:Spring \@ResponseBody Jackson JsonSerializer with JodaTimeSpring configure \@ResponseBody JSON format...
  • 谢谢 maricn...我没有自定义 ObjectMapper..如果可能的话我也不想拥有一个! ;-) 是的,我搜索了stackoverflow,但没有找到这个问题的任何答案。我错过了什么吗?
  • 这个类 RestResponse 是什么?
  • RestResponse 是一个 Wrapper 类,我会粘贴它。它将有一个返回研究的 getContent()。

标签: java rest spring-mvc inheritance jackson


【解决方案1】:

尽量只返回你需要的对象,不要把它包装在通用包装类中。您的问题与 Java 类型擦除有关。查看更多信息here

@ResponseBody
    public @ResponseBody Study getStudyById(@PathVariable("studyIdentifier")    String studyIdentifier) throws DAOException {

        return studyIdentifier;
    }

【讨论】:

  • 就是这样!因为我想保留 RestResponse 包装器,所以我创建了一个扩展 RestResponse 的类,如下所示:public class StudyRestResponse extends RestResponse&lt;Study&gt; { }。这样我就可以保留包装器,而且我想,类型擦除不再发生。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-05-25
  • 2011-09-10
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 2012-12-09
  • 2011-06-18
  • 2017-08-04
相关资源
最近更新 更多