jackson过滤属性分为静态和动态两种。

静态如下:

定义两个Bean 先,这两个bean 是父子关系。

  1. public class User {
  2. private String name;
  3. private Date createDate;
  4. private Set<Article> articles = Sets.newHashSet();
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. public Date getCreateDate() {
  12. return createDate;
  13. }
  14. public void setCreateDate(Date createDate) {
  15. this.createDate = createDate;
  16. }
  17. public Set<Article> getArticles() {
  18. return articles;
  19. }
  20. public void setArticles(Set<Article> articles) {
  21. this.articles = articles;
  22. }
  23. }
  1. public class Article {
  2. private String title;
  3. private User user;
  4. public String getTitle() {
  5. return title;
  6. }
  7. public void setTitle(String title) {
  8. this.title = title;
  9. }
  10. public User getUser() {
  11. return user;
  12. }
  13. public void setUser(User user) {
  14. this.user = user;
  15. }
  16. }

然后自己写的一个Jackson实用类

  1. public class Jacksons {
  2. private ObjectMapper objectMapper;
  3. public static Jacksons me() {
  4. return new Jacksons();
  5. }
  6. private Jacksons() {
  7. objectMapper = new ObjectMapper();
  8. // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
  9. objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
  10. objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
  11. objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
  12. }
  13. public Jacksons filter(String filterName, String... properties) {
  14. FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
  15. SimpleBeanPropertyFilter.serializeAllExcept(properties));
  16. objectMapper.setFilters(filterProvider);
  17. return this;
  18. }
  19. public Jacksons addMixInAnnotations(Class<?> target, Class<?> mixinSource) {
  20. objectMapper.getSerializationConfig().addMixInAnnotations(target, mixinSource);
  21. objectMapper.getDeserializationConfig().addMixInAnnotations(target, mixinSource);
  22. return this;
  23. }
  24. public Jacksons setDateFormate(DateFormat dateFormat) {
  25. objectMapper.setDateFormat(dateFormat);
  26. return this;
  27. }
  28. public <T> T json2Obj(String json, Class<T> clazz) {
  29. try {
  30. return objectMapper.readValue(json, clazz);
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. throw new RuntimeException("解析json错误");
  34. }
  35. }
  36. public String readAsString(Object obj) {
  37. try {
  38. return objectMapper.writeValueAsString(obj);
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. throw new RuntimeException("解析对象错误");
  42. }
  43. }
  44. @SuppressWarnings("unchecked")
  45. public List<Map<String, Object>> json2List(String json) {
  46. try {
  47. return objectMapper.readValue(json, List.class);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. throw new RuntimeException("解析json错误");
  51. }
  52. }
  53. }

最后是测试:

  1. public class Test {
  2. public static void main(String args[]) {
  3. User user = new User();
  4. user.setName("chris");
  5. user.setCreateDate(new Date());
  6. Article article = new Article();
  7. article.setTitle("title");
  8. article.setUser(user);
  9. Set<Article> articles = Sets.newHashSet(article);
  10. user.setArticles(articles);
  11. String userJson = Jacksons.me().readAsString(user);
  12. String articleJson = Jacksons.me().readAsString(article);
  13. System.out.println(userJson);
  14. System.out.println(articleJson);
  15. }
  16. }

1.父子关系引用

直接输出肯定是报循环错误,Jackson 提供了两个注解

@JsonManagedReference

public Set<Article> getArticles() {

return articles;

}

@JsonBackReference

public User getUser() {

return user;

}

打印结果为:{"name":"chris","createDate":"2012-04-18","articles":[{"title":"title"}]}, {"title":"title"}

2.@JsonIgnore注解

只说父子引用关系的。父子两边都加@JsonIgnore打印字符串为:

{"name":"chris","createDate":"2012-04-18"},{"title":"title"}

单向User加该注解

@JsonIgnore

public Set<Article> getArticles() {

return articles;

}

打印结果为:

{"name":"chris","createDate":"2012-04-18"}

{"title":"title","user":{"name":"chris","createDate":"2012-04-18"}}

单向Article 加该注解

@JsonIgnore

public User getUser() {

return user;

}

打印结果:

{"name":"chris","createDate":"2012-04-18","articles":[{"title":"title"}]}

{"title":"title"}

3.@JsonIgnoreType(没用过)

4.@JsonIgnoreProperties

这个加在类级别上, 用法很简单@JsonIgnoreProperties({"property1", "property2"})

动态过滤属性:

这个比较麻烦方法如下(有如下两种方法):

1.使用@JsonFilter注解

使用方法为先给ObjectMapper添加一个filter,然后还要在需要过滤的类上加@JsonFilter("filterName")注解。

比如说要过滤User 上的name属性,先

Jacksons.me().filter("myFilter", "name").readAsString(user),具体看Jacksons代码。并在User类上加@JsonFilter("myFilter")。

有点不爽的是如果用另外一个没有添加该filter的ObjectMapper解析的话会报错。

如果这个User类已经添加了@JsonFilter("myFilter")注解,但在另外一个地方又要解析它并不想过滤name 属性,那只能是

Jacksons.me().filter("myFilter", ""),然后在读出来。

如果要过滤多个属性可以如下:

Set<String> rolePros = new HashSet<String>();
rolePros.add("rank");
rolePros.add("areaId");
rolePros.add("areaName");
rolePros.add("areaCode");

Set<String> titleFilter = new HashSet<String>();
titleFilter.add("status");
titleFilter.add("ottVisible");
titleFilter.add("dvbVisible");
titleFilter.add("roleRelationList");

objectMapper = new ObjectMapper();
FilterProvider filterProvider = new SimpleFilterProvider().
addFilter("RoleFilter",SimpleBeanPropertyFilter.serializeAllExcept(rolePros)).
addFilter("TitleFilter", SimpleBeanPropertyFilter.serializeAllExcept(titleFilter));
objectMapper.setFilters(filterProvider);

写完这个后,还需要在需过滤的Bean上加@JsonFilter(filterName),

2.添加混入注解(暂时这么翻译)

定义一个接口或类先, 在该类上添加@JsonIgnoreProperties("name"), 然后在ObjectMapper的配置项上添加混入注解

输出为:

String mixInUser = Jacksons.me().addMixInAnnotations(User.class, MixInUser.class).readAsString(user);

System.out.println(mixInUser);

引自:http://yxb1990.iteye.com/blog/1489712

Jackson 过滤属性的更多相关文章

  1. (转)DataRow的各种状态和DataView的两种过滤属性

    DataRow的各种状态 http://www.cnblogs.com/zxjyuan/archive/2008/08/20/1271987.html 一个DataRow对象刚被创建之后(DataTa ...

  2. Jackson 动态过滤属性,编程式过滤对象中的属性

    场景:有时候我们做系统的时候,比如两个请求,返回同一个对象,但是需要的返回字段并不相同. 常见与写前端接口的时候,尤其是手机端,一般需要什么数据就返回什么样的数据.此时对于返回同一个对象我们就要动态过 ...

  3. java spring使用Jackson过滤

    一.问题的提出. 项目使用Spring MVC框架,并用jackson库处理JSON和POJO的转换.在POJO转化成JSON时,希望动态的过滤掉对象的某些属性.所谓动态,是指的运行时,不同的cont ...

  4. C#在数据层过滤属性中的主键

    C#使用泛型+反射做为数据层时,一个很都头疼的问题,如何让C#属性在程序里识别出哪个属性是主键,在拼接SQL时,不能把主键拼接到SQL语句里. 这个需要自定义一个属性.新建一个类文件,命名为Prosp ...

  5. shiro过滤器过滤属性含义

    securityManager:这个属性是必须的. loginUrl :没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/lo ...

  6. Maven过滤属性文件,替换属性值

    pom.xml 1.resources: resources中是定义哪些目录下的文件会被配置文件中定义的变量替换,一般我们会把项目的配置文件放在src/main/resources下,像db,bean ...

  7. Asp .Net MVC中常用过滤属性类

    /// <summary> /// /// </summary> public class AjaxOnlyAttribute : ActionFilterAttribute ...

  8. C# openfiledialog设置filter属性后达不到过滤效果的原因之一

    此处用RichTextBox控件举例>>> 在窗体对应的类中处理Load事件可以为openfiledialog设置Filter的属性: private void Form1_Load ...

  9. fastjson过滤不需要的属性

    以下是一个通用的对象转json的方法,使用的fastjson的SimplePropertyPreFilter 对象,个人感觉比使用PropertyPreFilter的匿名内部类形式的过滤器更好用!直接 ...

随机推荐

  1. hdu 4704(费马小定理+快速幂取模)

    Sum                                                                                Time Limit: 2000/ ...

  2. 如何在ashx处理页中获取Session值

    本文章摘自:http://www.cnblogs.com/vihone/archive/2010/06/04/1751490.html 在一般事务处理页面,可以轻松的得到 Request,Respon ...

  3. (Go)08.time示例

    package main import ( "fmt" "time" ) func test() { ) } func main() { now := time ...

  4. PCB 3D PCB 后续改进与扩展功能一些想法

    再次感受到WelGl实现3D效果的震撼, 一.目前功能: Gerber与钻孔 解析 并转为3D实景图,用户360度操控 二.后续改进扩展功能: 1.增加ODB++解析 2. 3D 尺寸标注(外形尺寸, ...

  5. JDBC-ODBC桥接器连接Access数据库

    今天,遇到一个问题,虽然不是什么大难题,但对于初学者来说也缠绕了我好久!(好气哦) 问题: 运行jsp项目连接不上数据库: java.sql.SQLException: [Microsoft][ODB ...

  6. unity3d引擎中slua的使用

    SLua是开源软件,没有反射,没有额外GC,采用静态代码生成,可以用于游戏核心逻辑,完整支持4.6+ UI系统. 1.下载安装 http://www.slua.net/ https://github. ...

  7. 文件的上传(可以上传照片,word文档,等单个文件)

    jsp: jsp页面: <LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css ...

  8. inline-block默认间距解决方法

    方法一: 父元素设置font-size: 0;  行内块元素有文字时再在该元素上设置font-size 方法二: 父元素设置word-spacing为负 方法三: Inline-block   元素浮 ...

  9. ASP.net获取当前url各种属性(文件名、参数、域名等)的方法

    假设当前页完整地址是:http://www.test.com/aaa/bbb.aspx?id=5&name=kelli "http://"是协议名 "www.te ...

  10. Dijkstra的双栈算术表达式求值算法 C++实现

    #include<iostream> #include<string> using namespace std; template<typename T> clas ...