简体   繁体   中英

Gson java.lang.IllegalArgumentException: No time zone indicator

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM