【发布时间】:2011-09-16 11:52:35
【问题描述】:
在 Jersey 中,当使用 Jackson 进行 JSON 序列化时,不包括实现子类的额外属性。例如,给定以下类结构
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="@class")
@JsonSubTypes({
@JsonSubTypes.Type(value = Foo.class, name = "foo")
}
public abstract class FooBase {
private String bar;
public String getBar() {
return bar;
}
public void setBar( String bar ) {
this.bar = bar;
}
}
public class Foo extends FooBase {
private String biz;
public String getBiz() {
return biz;
}
public void setBiz( String biz ) {
this.biz = biz;
}
}
还有下面的泽西代码
@GET
public FooBase get() {
return new Foo();
}
我得到以下 json
{"@class" => "foo", "bar" => null}
但我真正想要的是
{"@class" => "foo", "bar" => null, "biz" => null}
另外,在我的 web.xml 中,我启用了 POJOMappingFeature to solve this issue
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
编辑:修复了 Java 代码以正确设置 setter 并且 Foo 不是抽象的
【问题讨论】:
-
Foo类def真的是抽象的吗?
-
FWIW 仅使用 Jackson(不带 Jersey),该示例按预期序列化为 {"@class":"foo","biz":null,"bar":null}
-
修复了抽象的 Foo 问题
-
程序员 Bruce - 是的 - 我也发现了,如果我使用直接对象映射器,它会正确序列化 - 或者如果我返回 Object,它会正确序列化 - 只有当我使用抽象类作为返回类型时它没有正确序列化