How does @JsonView annotation can be used for nested entities? How does @JsonView annotation can be used for nested entities? json json

How does @JsonView annotation can be used for nested entities?


I had a similar problem, it's not exactly your problem but maybe the approach will be usefull for you.

I only use one ViewObject

public class Views {    public static class Low {    }    public static class Medium extends Low {    }    public static class High extends Medium {    }}

Every time that i have a nested object i need it in the Views.Low View, so i write a Serializer to do this.

public class Serializer extends JsonSerializer<Object> {    @Override    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {        ObjectMapper objectMapper = new ObjectMapper();        objectMapper.writerWithView(Views.Low.class).writeValue(jgen, value);    }} 

Finally in my objects i used like this:

public class Person {   @JsonView(Views.High.class)   @JsonSerialize(using = Serializer.class)   private Address address;}

The resource:

@Path("hey")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public class Resource {   @GET   @Path("/stack/overflow")   @JsonView(Views.High.class)   public Response method() {       //return Person entity in response with address low view   }   @GET   @Path("/stack/overflow")   @JsonView(Views.Medium.class)   public Response method() {       //return Person entity in response with no address   }}

You can use this approach to your problem, but if you use different Class Views you have to write a lot of Serializers.