Jackson json xmlgregoriancalendar deserializer

655 Views Asked by At

I have a problem with parsing json. It has a date for exapmle - "2014-01-07". And when it parses and became to createUserRequest.getBirthday() it contain - "2014-01-07T04:00:00.000+04:00". I need it in createUserRequest object, then I will assert it with another object. The question is how to get just "2014-01-07"?

In CreateUserRequest I have XMLGregorianCalendar variable and cannot change it.

protected XMLGregorianCalendar birthday;

Below just pulled out part of the code. Ignore class and variable names.

public class Test {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    public static <T> T parseJson(String pathname, Class<T> objectClass) throws Exception {
        return MAPPER.readValue(new File(pathname), objectClass);
    }

    public void parse() throws Exception {
        CreateUserRequest createUserRequest =
                Test.parseJson("src/test/resources/createUser.json", CreateUserRequest.class);
        System.out.println(createUserRequest.getBirthday());
    }
}
1

There are 1 best solutions below

2
On

LocalDate

Your Question is unclear. But if you are asking how to parse a date-only value represented in text as "2014-01-07", the answer is to parse as a LocalDate object.

LocalDate ld = LocalDate.parse( "2014-01-07" ) ;

The XMLGregorianCalendar class represents a moment, a date with time of day as seen in a particular time zone. For a date only value, this is the wrong class to use. Furthermore, this class is now legacy, supplanted years ago by the modern java.time classes.

The latest versions of Jackson support java.time.

Conversion

If handed a XMLGregorianCalendar object by code not yet updated to java.time, convert from that legacy class to the modern java.time classes.

Look to new conversion methods added to the old classes.

You need to convert your XMLGregorianCalendar object to ZonedDateTime by way of GregorianCalendar.

GregorianCalendar gc = myXmlGregorianCalendar.toGregorianCalendar() ;
ZonedDateTime zdt = gc.toZonedDateTime() ;

A ZonedDateTime represent a date with time of day as seen in a particular time zone. But you are interested in only the date portion. So extract a LocalDate object.

LocalDate ld = zdt.toLocalDate() ;

Compare to your target date with LocalDate#isEqual.

LocalDate target = LocalDate.parse( "2014-01-07" ) ;
if( ld.isEqual( target ) ) { … }