I use Google Gson
to map data from a json
file in Java
. But I encounter an error in the date format.
That's the mistake I saw;
Exception in thread "main" com.google.gson.JsonSyntaxException: Sat May 18 15:30:07 +0000 2019
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:87)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:75)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:46)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at app.producer.TwitterKafkaProducer.run(TwitterKafkaProducer.java:75)
at app.App.main(App.java:13)
Caused by: java.text.ParseException: Failed to parse date ["Sat May 18 15:30:07 +0000 2019"]: Invalid number: Sat
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:85)
... 10 more
Caused by: java.lang.NumberFormatException: Invalid number: Sat
at com.google.gson.internal.bind.util.ISO8601Utils.parseInt(ISO8601Utils.java:311)
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:129)
... 11 more
This is where I serialized the incoming json:
@SerializedName("created_at")
private Date createdAt;
My json object:
{
"created_at": "Sat May 18 16:11:36 +0000 2019",
"id": 1129781592514355205
}
I noticed that the error was caused by the failure of the formats. But in my research on how to fix this, I have no conclusions. I'd appreciate it if you could help me with this.
From this exception
Caused by: java.lang.NumberFormatException: Invalid number: Sat
It seems that your Gson is not correctly configure for input format Sat May 18 15:30:07 +0000 2019
so you should do something like this:
Gson gson = new GsonBuilder().setDateFormat("E MMM dd HH:mm:ss Z yyyy").create();