Yes, It's possible you can do it using Jackson @JsonView.
First you must create a class for declaring your views.
public class PersonResponseViews {
public static class Person { }
public static class Profile { }
}
Then you must include these changes in PersonResponse class
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class PersonResponse {
@JsonView(PersonResponseViews.Person.class)
String name;
@JsonView(PersonResponseViews.Person.class)
Profile profile;
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
Error error;
@JsonProperty("id")
@JsonView(PersonResponseViews.Profile.class)
int getProfileId() {
int id = 0;
if (profile != null) {
id = profile.id;
}
return id;
}
@JsonView({
PersonResponseViews.Person.class,
PersonResponseViews.Profile.class
})
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
static class Error {
String message;
int code;
}
@JsonView(PersonResponseViews.Person.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
static class Profile {
int id;
}
}
How to use your JSON views with a Spring Rest Controller
@JsonView(PersonResponseViews.Person.class)
@RequestMapping("/person")
public @ResponseBody
PersonResponse getPerson() {
PersonResponse resp = new PersonResponse();
resp.name = "first last";
resp.profile = new PersonResponse.Profile();
resp.profile.id = 1234;
resp.error = new PersonResponse.Error();
resp.error.code = 404;
resp.error.message = "some random error";
return resp;
}
@JsonView(PersonResponseViews.Profile.class)
@RequestMapping("/profile")
public @ResponseBody
PersonResponse getProfile() {
PersonResponse resp = new PersonResponse();
resp.profile = new PersonResponse.Profile();
resp.profile.id = 1234;
resp.error = new PersonResponse.Error();
resp.error.code = 404;
resp.error.message = "some random error";
return resp;
}
