Search code examples
javaspringspring-mvcjacksonjson-deserialization

Jackson deserialization ignore properties does not work properly with @JsonView


I'm using spring-framework 4.2.5 and Jackson 2.6.3 in my application. I use @jsonView for proper serializer entities. But It don't work properly for deserializer. For example I have an entity as follow:

public class A {

    @JsonView(View.Summary.class)
    private int a;

    @JsonView(View.Detail.class)
    private int b

    /*
     * Getters And Setters
     */
}

Now I have a controller as follow:

@RestController
@RequestMapping("/a")
public class AController {

     @RequestMapping("/add")
     @JsonView(View.Summary.class)
     public void add(@RequestBoddy A a)
     {
         // do Something
     }

} 

When I send a json as follow to this method:

{
   "a": 1,
   "b": 2
}

Because I use View.Summary.class JsonView for this method, It must ignore b, But it does not.

I use a config in Object mapper as follow: objectMapper.enable(DeserializerFeature.FAIL_ON_IGNORED_PROPERTIES)

Where is the problem?


Solution

  • Use @JsonView(View.Summary.class) on the parameter:

    @RequestMapping("/add")
    public void add(@RequestBoddy @JsonView(View.Summary.class) A a) {
        // do Something
    }
    

    And also, use Nullable types for your DTOs:

    public class A {
        @JsonView(View.Summary.class)
        private Integer a;
    
        @JsonView(View.Detail.class)
        private Integer b
    
        /*
         * Getters And Setters
         */
    }
    

    Otherwise, you won't be able to tell the Default Values and Missing Values apart.