Android处理java的date数据的问题

背景

直接在接口中转Date对象时候,Gson默认只会序列化/反序列化 Date().toString()后的字符串,类似 Oct 16, 2015 12:28:22 PM ,使用gson解析后台返回的数据时,无意发现了一个问题,如果使用 Date 类型的数据,将会出现这样的情形:

  • 数据:"firstDataTime" : { "date" : 29, "day" : 5, "hours" : 14, "minutes" : 37, "month" : 6, "seconds" : 14, "time" : 1469774234000, "timezoneOffset" : -480, "year" : 116 }
  • 解析时,就会出现两个问题:
  1. 必须按照对象来解析,这个,Date对象不是这样子的啊,直接按照Date型解析肯定出问题;
  2. 使用时基本上不会使用Date对象,都需要格式化或转换为String型的数据,所以也不能直接使用; 所以,使用时各种不方便,可是Gson这么强大的工具能考虑不到这个问题吗,显然不是,只是自己孤陋寡闻罢了
解决
  1. 定义一个抽象类,同时实现序列化和反序列化接口,如下 public abstract class GsonTypeAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {}
  2. 在使用gson解析时,集成上述GsonTypeAdapter,实现相应的序列化和反序列化方法,即可
  3. 解析,使用GsonBuilder.registerTypeAdapter,初始化Gson对象, Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new GsonTypeAdapter(){// 方法实现 } ).setDateFormat("yyyy-MM-dd HH:mm:ss").create();

给个例子:

Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {
    public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        String dateFormatAsString = format.format(new Date(src.getTime()));
        return new JsonPrimitive(dateFormatAsString);
    }
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!(json instanceof JsonPrimitive)) {
            throw new JsonParseException("The date should be a string value");
        }
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
            Date date = (Date) format.parse(json.getAsString());
            return new Timestamp(date.getTime());
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

其他,正常使用gson解析即可

转载于:https://my.oschina.net/Gxhpro/blog/744669

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值