Java DateDeserializers-class And Method Code Example


Here is an example of how to use the DateDeserializers class from the Jackson Databind library to deserialize a date from JSON:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateDeserializer extends StdScalarDeserializer<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public CustomDateDeserializer() {
        super(Date.class);
    }

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

You can then use this custom deserializer by registering it with the ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Date.class, new CustomDateDeserializer());
mapper.registerModule(module);

Then you can deserialize your JSON to Date as follow:

Date date = mapper.readValue(jsonString, Date.class);

Please note that the above example is just a skeleton code, you may need to handle the exception and add proper validation based on your use case and format of the date in the json.

You can also use the DateDeserializers class which have different deserializer for different types of date formats like ISO, timestamp etc

You can use it as

ObjectMapper mapper = new ObjectMapper();
DateDeserializers.add(module);
mapper.registerModule(module);

This will register the default date deserializers provided by jackson in the module and you can deserialize date using the mapper in the same way as above.