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. 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. My jackson version is 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.
You should use the annotation @JsonIgnore
on the field getter you dont want to see in the returned JSON
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
P p = (P) c;
So as a temporary workaround I added one more class extending P:
class G extends P {
public G(P p) {super(p);}
}
and added copy constructor to Parent class 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.