I've got Date field in my POJO and I use retrofit to parse JSON. In some cases returning value of this field can be empty or null. And I get error:
Caused by: java.text.ParseException: Unparseable date: "" (at offset 0)
at java.text.DateFormat.parse(DateFormat.java:618)
at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:105)
Is there any smart way to handle this exception with retrofit?
You should register a custom Deserializer
for the Date
class
GsonBuilder gBuilder = new GsonBuilder();
gBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { .... }
Gson gSon = gBuilder.create();
when the callback is invoked, check the content of the JsonElement
before formatting the date, and act accordingly.
Don't forget to call addConverterFactory
with the Gson instance you created. Eg
.addConverterFactory(GsonConverterFactory.create(gSon))