Best way to extend a method of Google library

404 Views Asked by At

I develop a Java program that using com.google.gson.Gson(gson-2.2.4.jar). The method will throw exception in case date format ISO 8601 (for example: "2015-06-22T09:26:27+0000")

com.google.gson.JsonSyntaxException: 2015-06-22T09:26:27+0000
    at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:107) ~[gson-2.2.4.jar:na]
    at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:82) ~[gson-2.2.4.jar:na]
    at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:35) ~[gson-2.2.4.jar:na]
    at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58) ~[gson-2.2.4.jar:na]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93) ~[gson-2.2.4.jar:na]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172) ~[gson-2.2.4.jar:na]
    at com.google.gson.Gson.fromJson(Gson.java:803) ~[gson-2.2.4.jar:na]
    at com.google.gson.Gson.fromJson(Gson.java:768) ~[gson-2.2.4.jar:na]
    at com.google.gson.Gson.fromJson(Gson.java:717) ~[gson-2.2.4.jar:na]
    at com.google.gson.Gson.fromJson(Gson.java:689) ~[gson-2.2.4.jar:na]

To fix it, I have 2 ways

  1. Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").create(); ==> apply for all gson objects ==> change ~50 positions

  2. Extract the library of google as an utility of my program and change the DefaultDateTypeAdapter.deserializeToDate() function to handle this error. After that I'll change the import from google library into my utility library ==> change ~ 20 files

What is the best way to do?

1

There are 1 best solutions below

0
On BEST ANSWER

Just use this type adapter:

https://raw.githubusercontent.com/google/gson/master/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java

    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new UtcDateTypeAdapter());
    final Gson gson = gsonBuilder.create();