9

I get this string from the server:

[
 {
  "title":"spoil the ones u love today",
  "startDateTime":"2014-08-10T20:10:36.7158Z"
 },
 {
  "title":"home made patisserie",
  "startDateTime":"2014-08-10T20:08:45.0218Z"
 }
]

and I try to parse it an object

    public class Offer implements Serializable {
        public String title;
        public Date startDateTime;
    }

Type collectionType = new TypeToken<ArrayList<Offer>>() {}.getType();

mOffersList.addAll((Collection<? extends Offer>) gson.fromJson(result, collectionType));

but when I define "startDate" as a Date

the collection I get back from gson is empty

When i define "startDate" as a String

the collection is filled correctly.

I want to change its date format. That's why I prefer saving it as a Date object.

I have tried

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create;

and yet Gson fails to parse the server's string into

Date startDateTime. Nothing is added to the mOffersList and it stays empty.

What am I doing wrong?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

1 Answers1

21

Only setting the required DateFormat is not sufficient.

You need to define an implementation of com.google.gson.JsonDeserializer. For ex.

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

  @Override
  public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
      String date = element.getAsString();

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      format.setTimeZone(TimeZone.getTimeZone("GMT"));

      try {
          return format.parse(date);
      } catch (ParseException exp) {
          System.err.println("Failed to parse Date:", exp);
          return null;
      }
   }
}

and then register the above deserializer:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
omerhakanbilici
  • 874
  • 1
  • 18
  • 26
Vaibhav Raj
  • 2,214
  • 4
  • 23
  • 39
  • 2
    but how will gson know when a date-json is to parsed? – Elad Benda2 Aug 22 '14 at 20:53
  • 9
    so why is `setDateFormat()` exist for gsonBuilder? not as a shortcut for trevial impelementaion? – Elad Benda2 Aug 22 '14 at 20:54
  • it throws "java.text.ParseException: Unparseable date: "2014-08-10T20:10:36.7158Z" (at offset 23)" when I run your code. please change to 'Z' instead of Z at the end – Elad Benda2 Aug 22 '14 at 21:02
  • although it works. I'll appreciate answer to my above questions in comments – Elad Benda2 Aug 22 '14 at 21:04
  • Actually Z is related to timezones. In your implementation you had not provided any timezone information to GSON.If you remove Z and try running your code, It should work fine. Because in this case its not related to anything specific to timezones, so GSON will parse it to local timezone. – Vaibhav Raj Aug 22 '14 at 21:08
  • 1
    I'll appreciate answer to my above questions in comments 1, 2 – Elad Benda2 Aug 22 '14 at 21:37
  • @EladBenda2, did you find answer to your questions (comments 1,2)? I am in the same situation now)) – Farid Jul 29 '18 at 16:52
  • In my, case overridden method never fired – Farid Jul 29 '18 at 18:49