简体   繁体   中英

Ignore fields during deserialization in spring?

I want to ignore some fields during deserialization of json data in spring. I cannot use @JsonIgnore as the same model will be used in different methods and different fields need to be ignored. I have tried to explain the situation with the below example.

class User
{
private String name;
private Integer id;
//getters and setters
}

This is the User class that will be used as model.

@RequestMapping(value = '/path1', method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<CustomResponse> loadUser1(@RequestBody User user){
    System.out.println(user.name);
    //user.id is not required here
}

This is the first method that will use user.name and ignore user.id.

@RequestMapping(value = '/path2', method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<CustomResponse> loadUser2(@RequestBody User user){
    System.out.println(user.id);
    //user.name is not required here
}

This is the second method that will use user.id and ignore user.name.

You can use @JsonFilter to achieve dynamic filtering.

First, create a filter using com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter and pass it to a filter provider com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider .

Then, declare this filter on your bean using @JsonFilter .

In your case, this will do it:

@JsonFilter("myFilter")
public class User {
    private String name;
    private int id;
    // Getters and setters
}

This will apply the filter on your POJO:

public MappingJacksonValue getFiltered() {
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("id"));
    User user = new User();
    user.setId(1);
    user.setName("Me");
    MappingJacksonValue jacksonValue = new MappingJacksonValue(user);
    jacksonValue.setFilters(filterProvider);
    return jacksonValue;
}

Edit: SimpleBeanPropertyFilter has factory methods to tender to almost all practical filtering scenarios. Use them appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM