java 序列化时排除指定属性

Posted 李慕白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 序列化时排除指定属性相关的知识,希望对你有一定的参考价值。

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

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中添加依赖

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的包含策略,看下面的实例:

Java代码  
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

Java代码 
@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 

http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null

http://www.cnblogs.com/yangy608/p/3936848.html

附件是json学习笔记

以上是关于java 序列化时排除指定属性的主要内容,如果未能解决你的问题,请参考以下文章

详解jackson注解(三)jackson包含属性、忽略属性的注解

JSON序列化(stringify)对象时排除某些属性的两种方法

如何从 Json 序列化中排除属性

Java序列化之排除被序列化字段(transient/静态变量)

Java序列化之排除被序列化字段(transient/静态变量)

Newtonsoft.Json 序列化 排除指定字段或只序列化指定字段