Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson serialize referenced object fields to root

Tags:

jackson

I am working on POC of jersey REST service to be consumed by js MVC framework. On one of the forms i need to return UserProfile object (serialized to JSON by Jackson) which will be used to pre-populate HTML form. On form submission only a subset of fields must be sent to server (since some fields like "role" are read-only and must not be changed) so input JSON will be mappped to UserProfileUpdateRequest object. From server-code maintenance point of view i would like to have have a relationship between these 2 objects, since UserProfileUpdateRequest will be a subset of UserProfile, so my first choice is to use composition: UserProfile contains UserProfileUpdateRequest. The problem is that when UserProfile is serialized to JSON by jackson, all properties of referenced UserProfileRequest instance will be wrapped in userProfileRequest field- what seems to be quite natural but is not acceptable for JS guys (or at least i was told it is not acceptable). Is there any way i could force jackson to "flat" root object and point for which referenced objects its properties must be serialized under root? A little example

class UserProfileRequest{
private String a;
private String b;
...
}

class UserProfile{
private String role;
...
private UserProfileRequest userProfileRequest;
}

So when UserProfile is serialized i got:

{"role":"admin",...,"userProfileRequest":{"a":"...","b":"...",...}}

but would like to get

{"role":"admin",...,"a":"...","b":"...",...}

I am using Jackson 1.9.7.

like image 623
user62058 Avatar asked Mar 07 '13 06:03

user62058


1 Answers

I think you are looking for the @JsonUnwrapped annotation.

class UserProfile{
    private String role;
    ...
    @JsonUnwrapped
    private UserProfileRequest userProfileRequest;
}

Edit: Here is the link to @JsonUnwrapped in Jackson 1.9.9, so it should be available in 1.9.7, too.

like image 130
nutlike Avatar answered Nov 24 '22 07:11

nutlike