Neria Nachum Neria Nachum - 2 months ago 7
Android Question

Gson omits hours when parsing Joda DateTime object

I have a Joda

DateTime
field in the object I receive from the server. For example, the field value is
2016-09-01T11:30:00.000+03:00
. Then, when calling
gson.toJson()
, the field is converted into a date-only string,
2016-09-01
.

Code:

final GsonBuilder builder = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeSerializer());
final Gson gson = builder.create();
String str = gson.toJson(response.body());


When debugging I noticed that my custom type adapter's
serialize
method is not called. Maybe I'm not understanding this correctly, but I was expecting the method to be used when converting object to JSON string (on the other hand,
deserialize
is called when using
gson.fromJson()
on a string).

This is the custom type adapter:

public class DateTimeSerializer implements JsonDeserializer<DateTime>, JsonSerializer<DateTime>
{
private static final DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.date();

@Override
public DateTime deserialize(final JsonElement je, final Type type, final JsonDeserializationContext jdc) throws JsonParseException {
final String dateAsString = je.getAsString();
return dateAsString.length() == 0 ? null : DATE_FORMAT.parseDateTime(dateAsString);
}

@Override
public JsonElement serialize(final DateTime src, final Type typeOfSrc,
final JsonSerializationContext context) {
return new JsonPrimitive(src == null ? "" : DATE_FORMAT.print(src));
}
}


Any idea why is it parsed this way and how to solve this? Thanks!

Answer

As stated in the comments, I was using ISODateTimeFormat.date() instead of ISODateTimeFormat.dateTime().

Comments