欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2014.08.05 ——— android Gson JsonDeserializer  

程序员文章站 2022-07-11 22:13:10
...
2014.08.05 ——— android Gson JsonDeserializer

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();