泽西和杰克逊的子类序列化不包括额外的属性 [英] Jersey and Jackson serialization of subclasses does not include extra attributes

查看:81
本文介绍了泽西和杰克逊的子类序列化不包括额外的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jersey中,当使用Jackson进行JSON序列化时,不包括实现子类的额外属性。例如,给定以下类结构

In Jersey, when using Jackson for JSON serialization, the extra attributes of an implementing subclass are not included. For example, given the following class structure

@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 解决此问题

Also, in my web.xml I have enabled 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不抽象

Fixed the Java code to have the setters set properly and Foo to not be abstract

推荐答案

它应该像你展示的那样工作;有一个可能的例外:如果启用JAXB注释(仅限),JAXB限制要求只使用getter / setter对来检测属性。
所以尝试为'biz'添加setter,看看是否会改变它。

It should work as you show; with one possible exception: if you enable JAXB annotations (only), JAXB restrictions mandate that only getter/setter pairs are used to detect properties. So try adding setter for 'biz' and see if that changes it.

Jackson注释不会出现这种情况;理想情况下,如果你结合杰克逊和JAXB注释(我认为泽西启用了两者)。
如果还启用了Jackson注释处理,在'getBiz'旁边添加@JsonProperty也应该可以解决问题。

This would not occur with Jackson annotations; and ideally not if you combine Jackson and JAXB annotations (I thought Jersey enabled both). If Jackson annotation processing is also enabled, adding @JsonProperty next to 'getBiz' should also do the trick.

最后除非你需要JAXB注释,否则你可以只是恢复使用Jackson注释 - 在我看来,JAXB注释的主要用例是你需要生成XML和JSON,并使用JAXB(通过Jersey)来实现XML。否则它们对JSON没用。

Finally unless you need JAXB annotations, you could just revert to using Jackson annotations only -- in my opinion, the main use case for JAXB annotations is if you need to produce both XML and JSON, and use JAXB (via Jersey) for XML. Otherwise they aren't useful with JSON.

这篇关于泽西和杰克逊的子类序列化不包括额外的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆