4

I have weird bug working with Gson.

I have created it like this

mGson = new GsonBuilder().registerTypeAdapter(beelineItemType, new ItemsDeserializer()).setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();

and my json object is like this:

"EpgStartDate" : "2018-08-16T18:00:00" 

but when I try to deserialize it I got this error:

ccom.google.gson.JsonSyntaxException: 2018-08-16T06:00:00

caused by: java.text.ParseException: Failed to parse date ["2018-08-16T06:00:00']: No time zone indicator (at offset 0)

Caused by: java.lang.IllegalArgumentException: No time zone indicator

I dont understand where to put time zone and how. I am in Serbia so where and how and what time zone to put. If someone can help that would be awesome :D

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Kimi95
  • 55
  • 1
  • 5
  • For Serbia you need a time zone of Europe/Belgrade, for example `ZoneId.of("Europe/Belgrade")`. I don’t know GSON and can’t tell you where to stick it. – Ole V.V. Aug 17 '18 at 12:34

1 Answers1

5

You should make Deserializer like this

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");
      format.setTimeZone(TimeZone.getTimeZone("GMT"));

      try {
          return format.parse(date);
      } catch (ParseException exp) {
          System.err.println(exp.getMessage());
          return null;
      }
   }
}

and then register the above deserializer:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53
  • 3
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Aug 17 '18 at 12:30
  • This works just fine, but i have to gson objects, and the one i posted where i set date format was not the one that did deserialization :D So i just add set date format on correct gson object and that worked just fine – Kimi95 Aug 17 '18 at 13:15