"Unparseable date: 1302828677828" trying to deserialize with Gson a millisecond-format date received from server

Alfonso picture Alfonso · Apr 15, 2011 · Viewed 33.4k times · Source

After 4 hours non-stop trying to resolve the problem I have decided to ask here if someone could help me.

The problem is that my Android client when tries to deserialize the data received from a server throw the "Unparseable: 1302828677828" exception.

I would like to know if it is possible to deserialize a millisecond-format date using Gson.

Answer

Peter O. picture Peter O. · Jan 22, 2012

Alfonso's comment:

Finally I got the solution:

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