美文网首页
Gson中Expose和SerializedName字段属性

Gson中Expose和SerializedName字段属性

作者: TragedyGo | 来源:发表于2017-01-14 22:34 被阅读0次

Expose类


packagecom.google.gson.annotations;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.FIELD})

public @interface Expose {

boolean serialize() default true;

boolean deserialize() default true;

}

其中很多人误解Expose认为是不反序列化,其实真正意思是区别Gson在解析对面类中需要序列化标志,其它没有被标记的 成员属性将不会被Gson所解析翻译(序列化于反序列化,看上面代码就懂了,默认都是true)

SerializedName类


package com.google.gson.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface SerializedName {    
       String value();
}

这货就是翻译 成员属性,让Gson解析对应字段名字,做映射

EG:

public class TapJoyBean implements Serializable {    
@Expose    
@SerializedName("Cost")    
public String Cost;    
@Expose    
@SerializedName("isFree")    
public String isFree;    
@Expose    
@SerializedName("Amount")    
public String Amount;

public String balcony;
public transient int x
}

其中balcony就不会被Gson所认识做序列化,既是在balcony上加@SerializedName("balcony") 也无法使用 transient 这个字段不是Gson的,但它能告诉Gson不要把它序列化成Json

相关文章

网友评论

      本文标题:Gson中Expose和SerializedName字段属性

      本文链接:https://www.haomeiwen.com/subject/qucybttx.html