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

﹥>﹥吖頭↗ 提交于 2019-12-06 03:03:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!