Search code examples
javajerseypojo

How to hide specific variables in Pojo classes while generating JSON responses


I am trying to hide some fields in a Pojo class while generating Json responses. Assume there are 4 variables in my java class. In the first response, I need all variables to be generated in the json object. For the next response, I only need 3 variables in the json object.

(The hiding part possibly be implemented when object creation and not inside the class implementation.) Is there a way to do this?


Solution

  • This can be achieved with @JsonView feature. This feature allows you to define multiple "views" = set of attributes, for a given class.

    Each view is a simple marker class. for convinience, you can put them all inside one wrapper class (it can even be the pojo class itself)

    public class PojoViews {
        public static class Response1{}
        public static class Response2{}
        public static class Response3{}
    }
    

    The view classes are specified as annotation for every attributre that is to be included in seralization

    public class Pojo {
    
        @JsonView({PojoViews.Response1.class, PojoViews.Response2.class, PojoViews.Response3.class})
        public String attr1;
        @JsonView({PojoViews.Response1.class, PojoViews.Response2.class, PojoViews.Response3.class})
        public int attr2;
        @JsonView({PojoViews.Response1.class, PojoViews.Response2.class})
        public double attr3;
        @JsonView(PojoViews.Response1.class)
        public boolean attr4;
    }
    

    at runtime, you can assign a particular view to produce desired set af attributes

    ObjectMapper mapper = new ObjectMapper();
    Class<?> view = Pojo.Response2.class;  // runtime assignment of view
    mapper.writerWithView(view).writeValue(System.out, pojo);