今天做一个模型时,使用Gson序列化配置。然后呢,因为模型设计涉及父子轮调,所以…死循环了。想到解决方法是转为json时忽略对父节点的序列化。
搜索了下,可能是搜索引擎不行或这个问题不是很常见,没找到正解。
自己搞定了,mark一下,兴许能帮到一些小伙伴。
现在是正题:
1、原理:
gson中提供了使用ExclusionStrategy(排除策略)实现对类或者域的序列化排除。
2、操作:
- 生成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; } }
- 创建注释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 { }
- 在不需要序列化的类上增加该注释:
/** * * Area model. * * @author neoliu6 * @version 创建时间:2016年3月3日 上午6:48:12 */ public class Area { @Ignore private Area parentArea; private String areaName; }
- Gson实例使用GsonBuilder创建,并添加排除初略类:
Area area = new Area("中国"); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.addSerializationExclusionStrategy(new IgnoreStrategy()); System.out.println(gsonBuilder.create().toJson(area ));
- 这样输出的时候就忽略了对父地区的序列化了。搞定。
mark 一下 晚上回家又查了些资料:
还有几种方式,上面的的方式可能优雅点。其他方法列举如下:
1、把需要过滤的字段修饰符transient
2、使用@Expose注解,但是这个对我而言不是很好理解?求高手解答为什么这么命名。
更新:
@Expose 注解是暴露得意思
注解在字段上,标识字段在对象转json时是否被序列化。(serialize,deserialize)