自定义JSON返回字段

今天看到一篇文章,里面介绍了如何自定义返回json字段,感觉挺好用的,这里学习一下。

实现工具类:

/**
* @author fengzp
* @date 17/2/20上午10:34
* @email fengzp@gzyitop.com
* @company 广州易站通计算机科技有限公司
*/
public class JsonFilter { private static final String INCLUDE = "JSON_INCLUDE";
private static final String EXCEPT = "JSON_EXCEPT"; @com.fasterxml.jackson.annotation.JsonFilter(INCLUDE)
interface MyJsonInclude {} @com.fasterxml.jackson.annotation.JsonFilter(EXCEPT)
interface MyJsonExcept {} public static String mapper(Object bean, Class<?> clazz, String include, String except) throws JsonProcessingException { if(clazz == null)
return null; ObjectMapper mapper = new ObjectMapper(); if(StringUtils.hasText(include)){
mapper.setFilterProvider(new SimpleFilterProvider().addFilter(INCLUDE,
SimpleBeanPropertyFilter.filterOutAllExcept(include.split(",")))); mapper.addMixIn(clazz, MyJsonInclude.class);
} if(StringUtils.hasText(except)){
mapper.setFilterProvider(new SimpleFilterProvider().addFilter(EXCEPT,
SimpleBeanPropertyFilter.serializeAllExcept(except.split(",")))); mapper.addMixIn(clazz, MyJsonExcept.class);
} return mapper.writeValueAsString(bean);
} }

测试:

public class User {
private Integer id; private String userName; private String password; private String realName; private Boolean status; private String email; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdAt; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updatedAt;

自定义JSON返回字段

自定义JSON返回字段

上一篇:Bitmap的分析与使用.md


下一篇:考前停课集训 Day5 累