Jackson动态处理返回字段
有时候业务需要动态返回字段,比如,
场景一:返回 name , birthday, createDate
场景二:返回name, birthday, age
现做个备忘录,以便参考。
下面是引入的POM
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
创建 JacksonJson过滤器类,代码如下:
@JsonFilter("JacksonFilter")
public class JacksonJsonFilter extends FilterProvider{
Map<Class<?>, Set<String>> includeMap = new HashMap<>();
Map<Class<?>, Set<String>> filterMap = new HashMap<>();
public void include(Class<?> type, String[] fields) {
addToMap(includeMap, type, fields);
}
public void filter(Class<?> type, String[] fields) {
addToMap(filterMap, type, fields);
}
private void addToMap(Map<Class<?>, Set<String>> map, Class<?> type, String[] fields) {
Set<String> filedSet=new HashSet<>();
if(fields!=null && fields.length>0){
for(String filed : fields){
filedSet.add(filed);
}
}
map.put(type, filedSet);
}
@Override
public BeanPropertyFilter findFilter(Object filterId) {
throw new UnsupportedOperationException("Access to deprecated filters not supported");
}
@Override
public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) {
return new SimpleBeanPropertyFilter() {
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider prov, PropertyWriter writer)
throws Exception {
if (apply(pojo.getClass(), writer.getName())) {
writer.serializeAsField(pojo, jgen, prov);
} else if (!jgen.canOmitFields()) {
writer.serializeAsOmittedField(pojo, jgen, prov);
}
}
};
}
public boolean apply(Class<?> type, String name) {
Set<String> includeFields = includeMap.get(type);
Set<String> filterFields = filterMap.get(type);
if (includeFields != null && includeFields.contains(name)) {
return true;
} else if (filterFields != null && !filterFields.contains(name)) {
return true;
} else if (includeFields == null && filterFields == null) {
return true;
}
return false;
}
}
写个Util工具类
public class JsonWareUtil {
private static ObjectMapper objectMapper = null;
private static JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();
static {
if(objectMapper==null){
objectMapper = new ObjectMapper();
// 允许对象忽略json中不存在的属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 允许出现特殊字符和转义符
objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// 允许出现单引号
objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
// 忽视为空的属性
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
}
public static void filter(Class<?> clazz, String include, String filter) {
if (clazz == null)
return;
if (StringUtils.isNotBlank(include)) {
jacksonFilter.include(clazz, include.split(","));
}
if (StringUtils.isNotBlank(filter)) {
jacksonFilter.filter(clazz, filter.split(","));
}
objectMapper.addMixIn(clazz, jacksonFilter.getClass());
}
/**
* @param obj 被转对象
* @return JSON串
* 将对象转JSON字符串
*/
public static String beanToJson(Object obj) {
try {
objectMapper.setFilterProvider(jacksonFilter);
String jsonString = objectMapper.writeValueAsString(obj);
return jsonString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
...
下面省略其他封装的JSON操作方法。
}
使用:
public class Test {
public static void mian(String[] args) {
// fields: name , birthday, createDate, age
A a = new A();
a.setName("test1");
a.setBirthday("xxxx-xx-xx");
a.setCreateDate("2019-05-12 12:22:21");
a.setAge(16);
JsonWareUtil.filter(A.getClass(), "name, birthday", null);
String json = JsonWareUtil.beanToJson(a);
System.out.println(json);
}
}