Friday, May 12, 2017

custom deserialize your field in jackson

Currently I'm doing an integration to a third party service api. I had a trouble while trying to deserialize a field as a Date. Their json contains a date field with an odd formatting. e.g. /Date(1494579066000)/
So I have to deserialize it into a date by taking the number between paranthesis, then casting it to a Date object.
Here is my model for json

public class Result implements Serializable
{
    @JsonProperty("InspectionDate")
    @JsonDeserialize(using = MyCustomDeserializer.class, as = Date.class)
    private Date inspectionDate;
...
}

As you can see I tell Jackson to use my class for deserialization.
Now it is time to write the custom deserializer.
I'm extending JsonDeserializer and overriding deserialize method.
jsonParser will give me the field value and I'm going to parse millisecond part of the text then cast it to a Date object.


public class MyCustomDeserializer extends JsonDeserializer
{
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException
    {
        String timestampAsString = jsonParser.getText();

        if (StringUtils.isEmpty(timestampAsString))
        {
            return null;
        }

        Matcher matcher = Pattern.compile("/Date\\(([0-9]+)\\)/").matcher(timestampAsString);

        if (!matcher.find())
        {
            return null;
        }

        String millisecondAsString = matcher.group(1);

        if (StringUtils.isEmpty(millisecondAsString))
        {
            return null;
        }

        return new Date(Long.parseLong(millisecondAsString));
    }
}