"Unparseable date:1302828677828"试图用Gson反序列化从服务器收到的毫秒格式日期

Alf*_*nso 76 serialization android json date gson

经过4个小时不停试图解决问题,我决定在这里询问是否有人可以帮助我.

问题是我的Android客户端在尝试反序列化从服务器收到的数据时会抛出"Unparseable:1302828677828"异常.

我想知道是否可以使用Gson反序列化毫秒格式的日期.

Pet*_* O. 136

阿方索的评论:

最后我得到了解决方案:

// Creates the json object which will manage the information received 
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();
Run Code Online (Sandbox Code Playgroud)

  • 当日期为两种格式时,这不起作用. (3认同)
  • `.getAsJsonPrimitive()` 可以省略,在 Java 8 lambdas 中它甚至更短:`Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, (JsonDeserializer) (json, typeOfT, context) -&gt; new Date( json.getAsLong())).create();` (2认同)
  • 拥有精确的“导入”行也将有所帮助。 (2认同)