首页 > 解决方案 > 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.

标签: javaspring-mvc

解决方案


可以使用@JsonFilter动态过滤来实现。

首先,使用创建过滤器com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter并将其传递给过滤器提供程序com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider

然后,使用 . 在您的 bean 上声明此过滤器@JsonFilter

在你的情况下,这将做到这一点:

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

这将在您的 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;
}

编辑: SimpleBeanPropertyFilter有工厂方法来投标几乎所有实际的过滤场景。适当地使用它们。


推荐阅读