1. Problem description

Invalid Time Zone Indicator “is reported today when deserializing JSON to Java bean using Gson. The detailed error log is as follows:

Caused by: com.google.gson.JsonSyntaxException: 1534467411000
        at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:74)
        at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:59)
        at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:41)
        at com.google.gson.internal.bind.TypeAdapters$26$1.read(TypeAdapters.java:598)
        at com.google.gson.internal.bind.TypeAdapters$26$1.read(TypeAdapters.java:596)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
        at com.google.gson.Gson.fromJson(Gson.java:887)
        at com.google.gson.Gson.fromJson(Gson.java:852)
        at com.google.gson.Gson.fromJson(Gson.java:801)
        at com.google.gson.Gson.fromJson(Gson.java:773)
        Caused by: java.text.ParseException: Failed to parse date ["1534467411000']: Invalid time zone indicator '0'
        at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274)
        at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:72)
        ... 19 more
Caused by: java.lang.IndexOutOfBoundsException: Invalid time zone indicator '6'
        at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:245)
        ... 20 more
Copy the code

In fact, Gson deserialized the time long to Date error, that is, Gson could not resolve the time format of the digits too long. This detailed analysis can see: blog.csdn.net/uniquewonde…

2. Procedure

(1) Solution 1

This error solution has an issue on Gson, which can be found at github.com/google/gson… . That is, create an object without using new Gson() and specify a dateFormat type.

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
Copy the code

It turns out that this method may not resolve the error.

(2) Solution 2

If method (1) fails to resolve the error, you are advised to use GsonBuilder to register the Date type.

GsonBuilder builder = new GsonBuilder(); 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();Copy the code

The analysis process can see: stackoverflow.com/questions/4…

You can choose two solutions according to the actual situation.