java 序列化时排除指定属性
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
范例:
- private String getMessageJson(PushMessage message) {
- List<Pattern> excludeProperties = new ArrayList<Pattern>();
- Pattern pattern1 = Pattern.compile("description");
- Pattern pattern2 = Pattern.compile("creator");// 创建者ID
- Pattern pattern3 = Pattern.compile("modifier");// 修改者ID
- Pattern pattern4 = Pattern.compile("deliverTime");//
- Pattern pattern5 = Pattern.compile("description");//
- Pattern pattern6 = Pattern.compile("createTime");//
- Pattern pattern7 = Pattern.compile("modifyTime");//
- excludeProperties.add(pattern1);
- excludeProperties.add(pattern2);
- excludeProperties.add(pattern3);
- excludeProperties.add(pattern4);
- excludeProperties.add(pattern5);
- excludeProperties.add(pattern6);
- excludeProperties.add(pattern7);
- String pushJsonStr = null;
- try {
- PushMessage pushMessage = null;
- try {
- pushMessage = message.clone();
- } catch (CloneNotSupportedException e) {
- logger.error("pushmessage clone failed.", e);
- }
- pushJsonStr = JSONUtil.serialize(pushMessage, excludeProperties,
- null, false, false);
- logger.info("after struts serialize:" + pushJsonStr);
- } catch (JSONException e) {
- logger.error("struts serialize failed.", e);
- }// TOOD 判断json字符串的长度是否超过了256
- return pushJsonStr;
- }
注意: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中添加依赖
- <!-- Json转化模块 -->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-lgpl</artifactId>
- <version>1.9.9</version>
- </dependency>
如何排除指定属性呢?
方式一:
先把要准备排除的属性的值设置为null
然后设置mapper的包含策略,看下面的实例:
- public void test_jackson(){
- // Map map=new HashMap();
- // map.put("name", "黄威");
- List<Student2> stus=null;
- stus=new ArrayList<Student2>();
- Student2 stu=new Student2();
- stus.add(stu);
- stu.setAddress(null);
- ObjectMapper mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Inclusion.NON_NULL);
- String content = null;
- try {
- content = mapper.writeValueAsString(stus);
- System.out.println(content);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
我把Student2对象的属性address设置为null,那么序列化时就会排除address属性.
注意:mapper.setSerializationInclusion(Inclusion.NON_NULL); 表示排除值为null的属性(成员变量)
方式二:使用FilterProvider
- @Test
- public void test_jackson2(){
- List<Student2> stus=null;
- stus=new ArrayList<Student2>();
- Student2 stu=new Student2();
- stus.add(stu);
- stu.setClassroom("36班");
- ObjectMapper mapper = new ObjectMapper();
- String content = null;
- try {
- // content = mapper.writeValueAsString(stus);
- SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("schoolNumber");
- FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
- content = mapper.writer(filters).writeValueAsString(stu);
- System.out.println(content);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
注意:在排除属性的对象上面增加注解:@JsonFilter("myFilter")
参考:http://www.baeldung.com/jackson-ignore-properties-on-serialization
java 序列化时排除指定属性的更多相关文章
- 7z压缩文件时排除指定的文件
分享一个7z压缩文件时排除指定文件类型的命令行,感觉很有用: 7z a -t7z d:\updateCRM.7z d:\updateCRM\*.* -r -x!*.log -x!*bak a:创建压缩 ...
- ZIP、tar.gz压缩时排除指定目录
1.ZIP 压缩时排除一个文件夹下所有内容zip -r sss.zip sss/ -x "sss/222/*" 压缩时排除指定多个文件夹下所有内容zip -r sss.zip ss ...
- Sublime Text 查找时排除指定的文件夹或文件
Sublime Text 查找时排除指定的文件夹或文件 Ctrl + Shift + F这组快捷键可以调出 Sublime Text 的查找替换窗口,里边有一栏 Where,可以做一些高级设置:d:\ ...
- FastJson序列化时过滤字段(属性)的方法总结
FastJson序列化时(即转成JSON字符串时),可以过滤掉部分字段,或者只保留部分字段,方法有很多,下面举一些常用的方法. 方法一.FastJson的注解 @JSONField(serialize ...
- Java序列化由于没有指定serialVersionUID导致报错
z.JobPersistenceException: Couldn't retrieve job because the BLOB couldn't be deserialized: com.mode ...
- GSON使用笔记(1) -- 序列化时排除字段的几种方式
http://blog.csdn.net/zxhoo/article/details/21471005 GSON是Google发布的JSON序列化/反序列化工具,非常容易使用.本文简要讨论在使用GSO ...
- grep时排除指定的文件和目录
参考:http://winterth.duapp.com/notes/ar03s04.htmlhttp://blog.sina.com.cn/s/blog_7169c8ce0100qkyf.html ...
- Java四舍五入时保留指定小数位数
方式一: double f = 3.1516; BigDecimal b = new BigDecimal(f); , BigDecimal.ROUND_HALF_UP).doubleValue(); ...
- C# Newtonsoft.Json JObject移除属性,在序列化时忽略
原文 C# Newtonsoft.Json JObject移除属性,在序列化时忽略 一.针对 单个 对象移除属性,序列化时忽略处理 JObject实例的 Remove() 方法,可以在 指定序列化时移 ...
随机推荐
- MarkdownPad2 下一些设置
MarkdownPad2注册码: 邮箱: Soar360@live.com 授权秘钥: GBPduHjWfJU1mZqcPM3BikjYKF6xKhlKIys3i1MU2eJHqWGImDHzWdD6 ...
- 旋转木马幻灯片切换效果JS源码详解
首先,放上慕课网的课程链接,源码是在这个课程里分享出来的,https://www.imooc.com/learn/386. 文章适合学习过这个课程的同学,再看这篇文章,可能有更深入的理解.主要是对各种 ...
- java之子类继承抽象类,子类构造器调用抽象类构造器问题
package com.wtd; public abstract class Car { private String name= "car"; public Car(String ...
- Sizzle源码分析:三 筛选和编译
好了有了之前的词法分析过程,现在我们来到select函数来,这个函数的整体流程,前面也大概说过: 1. 先做词法分析获得token列表 2. 如果有种子集合直接到编译过程 3. 如果没有种子集合并且是 ...
- New Concept English Two 14 34
recently busy a lot ,just practices every morning. $课文32 购物变得很方便 324. People are not so hone ...
- spring MVC 使用 modelAndView.setViewName("forward:*.action") 发送重定向
1.Servlet重定向forward与redirect: 使用servlet重定向有两种方式,一种是forward,另一种就是redirect.forward是服务器内部重定向,客户端并不知道服务器 ...
- Python数据类型-01.数字和布尔值
本节主要介绍Python中的基础知识中的数据类型,数字和布尔值 介绍几个知识点:1)内置函数print()的用法,直接打印括号里面的内容,或者print后跟多个输出,以逗号分隔.2)内置函数type( ...
- 新手学Appium_Python_Client
原文转自http://blog.sina.com.cn/s/blog_68f262210102v538.html 一,Appium_Python_Client的安装 推荐使用pip安装 pip ins ...
- test20181018 B君的第一题
题意 分析 考场爆零做法 考虑dp,用\(f(i,j,0/1)\)表示i及其子树中形成j个边连通块的方案数,其中i是否向外连边. \(O(n^3)\),转移方程太复杂就打挂了. #include< ...
- VUE的使用方法
vueInit: function() { var _this = this; this.vue = new Vue({ el: '#pa', data: { //存放初始化数据 sourceData ...