java - 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.
解决方案
可以使用@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
有工厂方法来投标几乎所有实际的过滤场景。适当地使用它们。
推荐阅读
- azure - 通过流量管理器 URL 访问网站时出现错误 404
- c# - 在 ASP.Net MVC 中没有身份验证的个人用户帐户
- java - 如何从资产文件夹中获取音乐文件的信息?
- sql-server - 仅当两个时间都存在时,计数才应返回
- python - 尝试使用 cx_oracle 从 python 连接 oracle db,并使用安装的 yum list 找到“ppcx_Oracle.i386: Python interface to Oracle”
- angular - 如何使用反应形式从输入中获取字符串
- x86-64 - 为什么不使用 RAX 在 System V AMD64 ABI 中传递参数?
- javascript - 设置 html 表单的选择输入
- c# - 致命:远程错误:需要验证码 - Bitbucket - Powershell 脚本
- java - 将在 netbeans 上创建的 JPanel 添加到另一个以编程方式创建的 Jpanel