简体   繁体   English

仅基类的Jersey / Jackson序列化问题

[英]Jersey/Jackson Serialization of base class only issue

Considering following example: 考虑以下示例:

class P { 
    int p = 0;
    public int getP() { return p; }
    public void setP(int p) { this.p = p; }
}

class C extends P { 
    int c = 0;
    public int getC() { return c; }
    public void setC(int c) { this.c = c; }
}

@GET
@Path("test")
@Produces(MediaType.APPLICATION_JSON)
public P testIt() {
    C c = new C();
    c.setP(2);
    P p = c;
    //p.setC(3) or p.getC() would produce error, expectedly
    return p;
}

I'd like my output to be just the fields from the base class, but I get childs fields as well. 我希望输出的只是基类中的字段,但是我也得到childs字段。 The examples' output is: 示例的输出为:

{ "p":2, "c":0 }

while I'd like it to be just: 而我希望它只是:

{ "p":2 }

Now I've seen posts on SO wanting behavior I have and having the behavior I need and didn't see single issue reported similar to mine. 现在,我已经看到有关我想要的行为和具有我需要的行为的帖子,并且没有看到单个问题的报告与我的相似。 This looks like bug rather than misconfiguration to me. 在我看来,这似乎是错误而不是错误的配置。

Any ideas what I might be doing wrong or any suggestions? 有什么想法我可能做错了什么或有什么建议吗? If someone needs some relevant information, just ask. 如果有人需要一些相关信息,请询问。 Thanks in advance! 提前致谢!

My jersey version is 2.22.1. 我的球衣版本是2.22.1。 My jackson version is 2.5.4. 我的杰克逊版本是2.5.4。

EDIT: 编辑:

I've tried using other version of jackson and in both 2.2.3 and 2.7.0 the behavior is the same. 我试过使用其他版本的杰克逊,在2.2.3和2.7.0中,行为是相同的。

You should use the annotation @JsonIgnore on the field getter you dont want to see in the returned JSON 您应该在不想在返回的JSON中看到的字段getter上使用注释@JsonIgnore

class C extends P { 
    int c = 0;
    @JsonIgnore
    public int getC() { return c; }
    public void setC(int c) { this.c = c; }
}

Otherwise try to cast your C class into P 否则,尝试将C类转换为P

P p = (P) c;

So as a temporary workaround I added one more class extending P: 因此,作为临时的解决方法,我添加了一个扩展P的类:

class G extends P {
    public G(P p) {super(p);}
}

and added copy constructor to Parent class P: 并将复制构造函数添加到父类P:

public P(P p) {this.p = p.getP();}

and in the code used it in following way: 并在代码中以以下方式使用了它:

public G testIt() {
    C c = new C();
    c.setP(2);
    P p = c;
    G g = new G(p);
    return g;
}

And now i have desired output. 现在我有想要的输出。

If noone finds a better way I'll just accept this one as correct answer soon. 如果没有人找到更好的方法,我将很快接受此方法作为正确答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM