Search code examples
javajsondatejacksonpojo

Date format Mapping to JSON Jackson


I have a Date format coming from API like this:

"start_time": "2015-10-1 3:00 PM GMT+1:00"

Which is YYYY-DD-MM HH:MM am/pm GMT timestamp. I am mapping this value to a Date variable in POJO. Obviously, its showing conversion error.

I would like to know 2 things:

  1. What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?
  2. In general, is there a way to process the variables before they get mapped to Object members by Jackson? Something like, changing the format, calculations, etc.

Solution

  • What is the formatting I need to use to carry out conversion with Jackson? Is Date a good field type for this?

    Date is a fine field type for this. You can make the JSON parse-able pretty easily by using ObjectMapper.setDateFormat:

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
    myObjectMapper.setDateFormat(df);
    

    In general, is there a way to process the variables before they get mapped to Object members by Jackson? Something like, changing the format, calculations, etc.

    Yes. You have a few options, including implementing a custom JsonDeserializer, e.g. extending JsonDeserializer<Date>. This is a good start.