2014.08.05 ——— android Gson JsonDeserializer

2014.08.05———androidGsonJsonDeserializer

Gson用起来很方便,但是有的时候需要对某一个字段进行特殊处理的时候,就比较麻烦,这个时候我们需要JsonDeserializer

需求:

服务器返回的是秒,我需要将其转换为毫秒

解决:

import java.lang.reflect.Type;

import com.google.xlgson.JsonDeserializationContext;
import com.google.xlgson.JsonDeserializer;
import com.google.xlgson.JsonElement;
import com.google.xlgson.JsonObject;
import com.google.xlgson.JsonParseException;

public class FavoriteRecordJsonType implements JsonDeserializer<FavoriteRecordPo>{

    @Override
    public FavoriteRecordPo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        FavoriteRecordPo tInfo = new FavoriteRecordPo();
        JsonObject tJson = json.getAsJsonObject();
        tInfo.movietitle = tJson.get("movietitle").getAsString();
        tInfo.movieid = tJson.get("movieid").getAsLong();
        tInfo.movietype = tJson.get("movietype").getAsString();
        
        tInfo.storetime = tJson.get("storetime").getAsLong() * 1000;
        return tInfo;
    }

}
       
GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(FavoriteRecordPo.class, new FavoriteRecordJsonType());
        gson = builder.create();

相关推荐