Reputation: 5377
I'm using GSON to deserialise some JSON. The JSON is:
{
"employee_id": 297,
"surname": "Maynard",
"givenname": "Ron",
"lastlogin": "",
...
The Employee Object has a Date field lastlogin:
public class Employee {
private Integer employee_id;
private String surname;
private String givenname;
private Date lastlogin;
The problem I have is that when the lastlogin value isn't populated, it's an empty String in the JSON, so the GSON parser throws:
java.text.ParseException: Unparseable date: ""
at java.text.DateFormat.parse(DateFormat.java:337)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:66)
What's the usual way around this?
Upvotes: 13
Views: 11092
Reputation: 11616
If you can't control the input (i.e. the JSon generating part) but know the format as it should be when not empty, you should just write an own deserializer that can handle empty values, like e.g.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Gson gson = gsonBuilder.create();
See https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ
Upvotes: 41
Reputation: 7521
That's because it is an empty string, which Date doesn't know how to handle. If you look at the GSON Code it shows that it's just blindly parsing the string using DateFormat.parse, which doesn't handle quote marks well.
Have you tried using null? Try using null if it is empty. From the code for GSON Code for DateTypeAdapter, it handles JSONNull objects fine, it just skips over them.
Upvotes: 2