Gson转json时忽略对某域的序列化


今天做一个模型时,使用Gson序列化配置。然后呢,因为模型设计涉及父子轮调,所以…死循环了。想到解决方法是转为json时忽略对父节点的序列化。

搜索了下,可能是搜索引擎不行或这个问题不是很常见,没找到正解。

自己搞定了,mark一下,兴许能帮到一些小伙伴。

 

现在是正题:

 

1、原理:

gson中提供了使用ExclusionStrategy(排除策略)实现对类或者域的序列化排除。

 

2、操作:

  1. 生成ExclusionStrategy实现类:
    import java.lang.annotation.Annotation;
    import java.util.Collection;
    
    import com.google.gson.ExclusionStrategy;
    import com.google.gson.FieldAttributes;
    
    /**
     *@author neoliu6
     *@version 创建时间:2016年3月3日 上午11:04:37
     */
    /**
     * @author neoliu6
     *
     */
    public class IgnoreStrategy implements ExclusionStrategy {
    
    	/*
    	 * (non-Javadoc)
    	 * 
    	 * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class)
    	 */
    	@Override
    	public boolean shouldSkipClass(Class<?> clazz) {
    		return false;
    	}
    
    	/*
    	 * (non-Javadoc)
    	 * 
    	 * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.
    	 * FieldAttributes)
    	 */
    	@Override
    	public boolean shouldSkipField(FieldAttributes fieldAttributes) {
    		Collection<Annotation> annotations = fieldAttributes.getAnnotations();
    		for (Annotation annotation : annotations) {
    			if (annotation.annotationType() == Ignore.class) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    }
  2. 创建注释Ignore:
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * @author neoliu6
     * @version 创建时间:2016年3月3日 上午10:52:53
     */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Ignore {
    }
    
  3. 在不需要序列化的类上增加该注释:
    /**
     *
     * Area model. 
     *
     * @author neoliu6
     * @version 创建时间:2016年3月3日 上午6:48:12
     */
    public class Area {
        @Ignore
        private Area parentArea;
        private String areaName;
    }
  4. Gson实例使用GsonBuilder创建,并添加排除初略类:
    Area area = new Area("中国");
    GsonBuilder gsonBuilder = new GsonBuilder();
    		gsonBuilder.addSerializationExclusionStrategy(new IgnoreStrategy());
    		System.out.println(gsonBuilder.create().toJson(area ));
  5. 这样输出的时候就忽略了对父地区的序列化了。搞定。

 

mark 一下 晚上回家又查了些资料:

还有几种方式,上面的的方式可能优雅点。其他方法列举如下:

1、把需要过滤的字段修饰符transient

2、使用@Expose注解,但是这个对我而言不是很好理解?求高手解答为什么这么命名。

更新:

@Expose 注解是暴露得意思

注解在字段上,标识字段在对象转json时是否被序列化。(serialize,deserialize)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值