時(shí)間類型的問題
當(dāng)我們?yōu)閭鬏攨f(xié)議寫B(tài)ean的時(shí)候,時(shí)間屬性通常情況下都是時(shí)間戳的形式,然而當(dāng)我們將其定義為Date格式時(shí)Gson默認(rèn)是不支持的,其轉(zhuǎn)換格式為:"mDate":"Mar 20, 2017 4:49:01 PM",因此我們會(huì)改為定義成long的格式。其實(shí)我們可以手動(dòng)處理一下:
public class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
}
public class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}
public class GsonBuilderUtil {
public static Gson create() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
gsonBuilder.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
Gson gson = gsonBuilder.create();
return gson;
}
}
此時(shí)我們就可以在Bean中定義Date屬性,調(diào)用Gson gson = GsonBuilderUtil.create();得到正確的格式:"mDate":1490000417888;
int,long,boolean的問題
當(dāng)我們的Bean中存在int、long、boolean類型的數(shù)據(jù)時(shí),不管你是否有對(duì)其賦值,使用Gson對(duì)該Bean使用toJson時(shí),都會(huì)默認(rèn)為其初始化并添加進(jìn)轉(zhuǎn)換后的字符串中,如下所示:
DateBean dateBean = new DateBean();
dateBean.setString("ass");
LogUtil.e("YXH", GsonBuilderUtil.create().toJson(dateBean));
得到的結(jié)果是:
{"mString":"ass","mDate":1490000862734,"mLong":0,"mInt":0,"mBoolean":false}
我們可以將其定義成Integer、Long、Boolean來規(guī)避此問題。