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!

Answers


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


Need Your Help

How can I convert a string to an array of strings in perl?

arrays string perl count

I am attempting to write a script that will take both a string and a single character from the command line, and then search the string for the single character for the number of occurrences. I have

GetComputerName WinApi call and %COMPUTERNAME% environment variable

windows winapi

Does the WinAPI call GetComputerName and reading %COMPUTERNAME% environment variable ALWAYS return the same result on Windows?