项目使用Gson来解析json,当服务器下发日期的Long类型时报错:
Caused by: java.text.ParseException: Failed to parse date ["1461689198000']: Invalid time zone indicator '9' (at offset 0)
简单而言是类型转换不过。需要我们自定义和注册适配器:
GsonBuilder builder = new GsonBuilder();
// Register an adapter to manage the date types as long values
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
参考文章
https://segmentfault.com/q/1010000005014254
https://stackoverflow.com/questions/5671373/unparseable-date-1302828677828-trying-to-deserialize-with-gson-a-millisecond
- (1)stackoverflow真是解决开发问题之利器。
- (2)使用fastjson不会出现上面的情况。
网友评论