@JsonDeserialize

@JsonDeserialize is used to indicate the use of a custom deserializer.

Let's see how that plays out - we'll use @JsonDeserialize to deserialize the eventData property with the CustomDateDeserializer

public class Event {
    public String name;

    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date date;
}

Here's the customer deserializer

public class CustomDateDeserializer extends StdDeserializer<Date>{
    private static SimpleDateFormat formatter =
            new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateDeserializer() {
        this(null);
    }
    protected CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String date = p.getText();
        try {
            return formatter.parse(date);
        } catch (ParseException ex) {
            return new Date();
        }
    }
}

And here's the back-back test:

    @Test
    public void test03() throws Exception {
        String json
                = "{\"name\":\"party\",\"date\":\"20-12-2014 02:30:00\"}";
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        ObjectMapper mapper = new ObjectMapper();
        Event event = mapper.readValue(json, Event.class);
        Assert.assertEquals("20-12-2014 02:30:00",sdf.format(event.getDate()));
    }

results matching ""

    No results matching ""