Gson转Json字符串时将日期类型转换成Long型的方法

有些特定需求, 比如说搜索引擎, 很多人都要求时间必须是时间戳. 所以, 我们把时间转成最原始的Long型. Gson默认的是不支持的, 需要手动处理一下.

日期转Long

public class DateSerializer implements JsonSerializer<Date> {    
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {              
        return new JsonPrimitive(src.getTime());    
    }
}

Long转日期

public class DateDeserializer implements JsonDeserializer<Date> {    
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {        
        return new java.util.Date(json.getAsJsonPrimitive().getAsLong());    
    }
}

构造通用工具类

public class GsonUtils {
    private static Gson instance = null;
    public synchronized static Gson getGson(){
        if(instance == null) {
            GsonBuilder builder = new GsonBuilder();
            builder.addSerializationExclusionStrategy(new IgnoreStrategy());
            builder.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
            builder.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
            instance = builder.create();
        }
        return instance;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容