Ok, I was close, but made a small (and pretty obvious) mistake..
Instead of:
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
I need to use:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
EDIT:
I now use a deseralizer as well, but only in my Android part. The reason why I changed it is as follows:
- When I had a differently formatted date or a date that was null, I would get a JsonParseException on the entire JSON, so none of my Order-Objects were created.
- Now that I use this seralizer and a Date appears to be of an invalid format or null, it just makes that Date in the Order-object null, but still converts everything as it should with a resulting Order-list.
Code:
try{
// Convert JSON-string to a List of Order objects
Type listType = new TypeToken<ArrayList<Order>>(){}.getType();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try{
return df.parse(json.getAsString());
}
catch(ParseException ex){
return null;
}
}
});
Gson dateGson = gsonBuilder.create();
orders = dateGson.fromJson(json, listType);
}
catch(JsonParseException ex){
ex.printStackTrace();
}