基于Jackson的JsonFilter实现动态数据填写
基于Jackson的JsonFilter实现动态数据修改,虽说是动态修改,其实也可以做加密,过滤等操作,直接看代码:
public class User {
private String name;
private String password;
//这个字段我想通过Filter自动填写
private String av;
}
如果不做任何操作的话,获取到的数据大概是这样的:
{
"name": "Gas",
"password": "1234567",
"av": "如果没有赋值的话,这里是空的"
}
在 User 类上添加注解 @JsonFilter
@JsonFilter("av_create")
public class User {
//...
}
创建一个自定义的 Filter
public class AvCreateFilter extends SimpleBeanPropertyFilter {
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
throws Exception {
System.err.println(writer.getFullName().getSimpleName());
if(writer.getFullName().getSimpleName().equals("av")){
User user = (User) pojo;
//设置 av 为 name-password
user.setAv(user.getName() + "-" + user.getPassword());
writer.serializeAsField(user,jgen,provider);
}else {
writer.serializeAsField(pojo,jgen,provider);
}
}
}
将他加入到 Jackson 中:
@Configuration
public class JacksonConfig {
@Bean
@Primary
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.createXmlMapper(false).build();
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.addFilter("av_create", new AvCreateFilter());
mapper.setFilterProvider(filterProvider);
return mapper;
}
}
这样就大概成功了,获取到的 Json 大概如下:
{
"name": "Gas",
"password": "1234567",
"av": "Gas-1234567"
}