java 序列化对象如何排除指定属性呢?

java 中序列化对象有多种方式:struts2 ,jackson,json-lib

(1)使用struts2 json插件

依赖的jar包:struts2-json-plugin-2.3.15.3.jar,xwork-core-2.3.15.3.jar,当然还有servlet-api.jar

范例:

  1. private String getMessageJson(PushMessage message) {
  2. List<Pattern> excludeProperties = new ArrayList<Pattern>();
  3. Pattern pattern1 = Pattern.compile("description");
  4. Pattern pattern2 = Pattern.compile("creator");// 创建者ID
  5. Pattern pattern3 = Pattern.compile("modifier");// 修改者ID
  6. Pattern pattern4 = Pattern.compile("deliverTime");//
  7. Pattern pattern5 = Pattern.compile("description");//
  8. Pattern pattern6 = Pattern.compile("createTime");//
  9. Pattern pattern7 = Pattern.compile("modifyTime");//
  10. excludeProperties.add(pattern1);
  11. excludeProperties.add(pattern2);
  12. excludeProperties.add(pattern3);
  13. excludeProperties.add(pattern4);
  14. excludeProperties.add(pattern5);
  15. excludeProperties.add(pattern6);
  16. excludeProperties.add(pattern7);
  17. String pushJsonStr = null;
  18. try {
  19. PushMessage pushMessage = null;
  20. try {
  21. pushMessage = message.clone();
  22. } catch (CloneNotSupportedException e) {
  23. logger.error("pushmessage clone failed.", e);
  24. }
  25. pushJsonStr = JSONUtil.serialize(pushMessage, excludeProperties,
  26. null, false, false);
  27. logger.info("after struts serialize:" + pushJsonStr);
  28. } catch (JSONException e) {
  29. logger.error("struts serialize failed.", e);
  30. }// TOOD 判断json字符串的长度是否超过了256
  31. return pushJsonStr;
  32. }

注意:Pattern.compile 的参数就是要排除的成员变量名称(即description,creator,modifier都是成员变量名称)

(2)使用Jackson

官网:http://jackson.codehaus.org/

参考:http://blog.csdn.net/sciurid/article/details/8624107

http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html

依赖的jar:jackson-mapper-lgpl-1.9.9.jar,jackson-core-lgpl-1.9.9.jar

如果使用maven,则在pom.xml中添加依赖

  1. <!-- Json转化模块 -->
  2. <dependency>
  3. <groupId>org.codehaus.jackson</groupId>
  4. <artifactId>jackson-mapper-lgpl</artifactId>
  5. <version>1.9.9</version>
  6. </dependency>

如何排除指定属性呢?

方式一:

先把要准备排除的属性的值设置为null

然后设置mapper的包含策略,看下面的实例:

  1. public void test_jackson(){
  2. //      Map map=new HashMap();
  3. //      map.put("name", "黄威");
  4. List<Student2> stus=null;
  5. stus=new ArrayList<Student2>();
  6. Student2 stu=new Student2();
  7. stus.add(stu);
  8. stu.setAddress(null);
  9. ObjectMapper mapper = new ObjectMapper();
  10. mapper.setSerializationInclusion(Inclusion.NON_NULL);
  11. String content = null;
  12. try {
  13. content = mapper.writeValueAsString(stus);
  14. System.out.println(content);
  15. } catch (JsonGenerationException e) {
  16. e.printStackTrace();
  17. } catch (JsonMappingException e) {
  18. e.printStackTrace();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }

我把Student2对象的属性address设置为null,那么序列化时就会排除address属性.

注意:mapper.setSerializationInclusion(Inclusion.NON_NULL); 表示排除值为null的属性(成员变量)

方式二:使用FilterProvider

  1. @Test
  2. public void test_jackson2(){
  3. List<Student2> stus=null;
  4. stus=new ArrayList<Student2>();
  5. Student2 stu=new Student2();
  6. stus.add(stu);
  7. stu.setClassroom("36班");
  8. ObjectMapper mapper = new ObjectMapper();
  9. String content = null;
  10. try {
  11. //          content = mapper.writeValueAsString(stus);
  12. SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("schoolNumber");
  13. FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
  14. content = mapper.writer(filters).writeValueAsString(stu);
  15. System.out.println(content);
  16. } catch (JsonGenerationException e) {
  17. e.printStackTrace();
  18. } catch (JsonMappingException e) {
  19. e.printStackTrace();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }

注意:在排除属性的对象上面增加注解:@JsonFilter("myFilter")

参考:http://www.baeldung.com/jackson-ignore-properties-on-serialization

java 序列化时排除指定属性的更多相关文章

  1. 7z压缩文件时排除指定的文件

    分享一个7z压缩文件时排除指定文件类型的命令行,感觉很有用: 7z a -t7z d:\updateCRM.7z d:\updateCRM\*.* -r -x!*.log -x!*bak a:创建压缩 ...

  2. ZIP、tar.gz压缩时排除指定目录

    1.ZIP 压缩时排除一个文件夹下所有内容zip -r sss.zip sss/ -x "sss/222/*" 压缩时排除指定多个文件夹下所有内容zip -r sss.zip ss ...

  3. Sublime Text 查找时排除指定的文件夹或文件

    Sublime Text 查找时排除指定的文件夹或文件 Ctrl + Shift + F这组快捷键可以调出 Sublime Text 的查找替换窗口,里边有一栏 Where,可以做一些高级设置:d:\ ...

  4. FastJson序列化时过滤字段(属性)的方法总结

    FastJson序列化时(即转成JSON字符串时),可以过滤掉部分字段,或者只保留部分字段,方法有很多,下面举一些常用的方法. 方法一.FastJson的注解 @JSONField(serialize ...

  5. Java序列化由于没有指定serialVersionUID导致报错

    z.JobPersistenceException: Couldn't retrieve job because the BLOB couldn't be deserialized: com.mode ...

  6. GSON使用笔记(1) -- 序列化时排除字段的几种方式

    http://blog.csdn.net/zxhoo/article/details/21471005 GSON是Google发布的JSON序列化/反序列化工具,非常容易使用.本文简要讨论在使用GSO ...

  7. grep时排除指定的文件和目录

    参考:http://winterth.duapp.com/notes/ar03s04.htmlhttp://blog.sina.com.cn/s/blog_7169c8ce0100qkyf.html ...

  8. Java四舍五入时保留指定小数位数

    方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); , BigDecimal.ROUND_HALF_UP).doubleValue(); ...

  9. C# Newtonsoft.Json JObject移除属性,在序列化时忽略

    原文 C# Newtonsoft.Json JObject移除属性,在序列化时忽略 一.针对 单个 对象移除属性,序列化时忽略处理 JObject实例的 Remove() 方法,可以在 指定序列化时移 ...

随机推荐

  1. springboot问题集(一)------junit内Assert.assertEquals()的含义

    1. assertEquals([String message],Object target,Object result) target与result不相等,中断测试方法,输出message asse ...

  2. EPANET头文件解读系列2——ENUMSTXT.H

    在前一系统中介绍了text.h,回顾下,该文件包含了EPANET中所有字符串常量的定义,而ENUMSTXT.H文件则是以text.h中定义的字符串常量为基础,来对这些字符串常量进行合理的分组,形成字符 ...

  3. 用压测模拟并发、并发处理(synchronized,redis分布式锁)

    使用工具:Apache an 测压命令: ab -n 100 -c 100 http://www.baidu.com -n代表模拟100个请求,-c代表模拟100个并发,相当于100个人同时访问 ab ...

  4. .net 面试题总结

    1. DataSet和DataReader的区别? DataReader:和数据库处于一直连接状态.只读只能向前读取,一次只能读取一行信息.DataReader每次只在内存中加载一条数据,内存占用少, ...

  5. 深入了解 Session 与 Cookie

    Java —— 深入了解 Session 与 Cookie Java web   了解Cookie和Session   定义 1.很通俗的来讲,Cookie就是浏览器的缓存,就是用户访问网站时保存在浏 ...

  6. POI使用 (4.0) 常用改动

    POI 升级到高版本后,原有的EXCLE导入导出工具类部分代码已不适用,目前只是对我自己写的工具类的过期代码进行更新,以后继续更新 若有问题请指出,再修改 1.数据类型 Cell.CELL_TYPE_ ...

  7. 【Beanstalkd】Beanstalkd消息队列的安装与使用

    一.Beanstalkd是什么? Beanstalkd是一个高性能,轻量级的分布式内存队列 二.Beanstalkd特性 1.支持优先级(支持任务插队)2.延迟(实现定时任务)3.持久化(定时把内存中 ...

  8. CollabNet Subversion Edge 安装笔记(1):基本安装设定篇

    转载于:http://blog.miniasp.com/post/2011/12/30/CollabNet-Subversion-Edge-Installation-Notes-Part-1-Basi ...

  9. 2.运行成功的Demo(Python+Appium)

    1.打开Appium运行 2.在Pycharm输入代码如下所示: from appium import webdriver desired_caps = {} #初始化 desired_caps['p ...

  10. jeecms一些经典标签

    http://www.121ask.com/thread-5512-1.html [@cms_channel_list]标签详细介绍 http://www.jeecmstheme.com/2014/0 ...