您的位置:首页 > 其它

Gson序列化字段排除

2017-08-30 00:00 417 查看
一个类有6个属性 ,用Gson进行序列化和反序列化,其中有1个属性需要排除。

方式一:通过@Expose排除

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Expose {

/**
* If {@code true}, the field marked with this annotation is written out in the JSON while
* serializing. If {@code false}, the field marked with this annotation is skipped from the
* serialized output. Defaults to {@code true}.
* @since 1.4
*/
public boolean serialize() default true;

/**
* If {@code true}, the field marked with this annotation is deserialized from the JSON.
* If {@code false}, the field marked with this annotation is skipped during deserialization.
* Defaults to {@code true}.
* @since 1.4
*/
public boolean deserialize() default true;
}

启用@Expose

Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()//只序列化和反序列化带Expose注解属性
.create();

备注:序列化字段必须添加@Expose注解,如果不添加属性将不会序列化

public class ExposeUser {

public static int expStatic;//Gson默认情况会排除带有static关键字属性

@Expose
public String name;//姓名
@Expose
public int age;//年龄
@Expose
public String sex;//性别
@Expose
public int height;//身高
@Expose
public float weight;//体重
public boolean isLogin;//是否登录

@Override
public String toString() {
return "{\"expStatic\":\"" + expStatic
+ "\",\"name\":\"" + name
+ "\",\"age\":\"" + age
+ "\",\"sex\":\"" + sex
+ "\",\"height\":\"" + height
+ "\",\"weight\":\"" + weight
+ "\",\"isLogin\":\"" + isLogin + "\"}";
}
}

方式二:不开启注解的情况下使用transient修饰

private transient boolean checked = true;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Gson 序列化 排除