среда, 22 октября 2014 г.

Java Jackson 1. Serialize\Deserialize java.util.Date <-> JSON

In WebSphere Application Server 8.5.5 there is built in support for developing REST services with Jackson 1 and Apache wink projects.
How can you work with dates in jackson 1?



Here is example of bean:
public class Applicant{
private Date  birthDate;

public Date getBirthDate(){
 return birthDate;
}

public void setBirthDate(Date date){
this.birthDate = date;
}
}

In json you need to pass back and forth the birthDate in format like "dd-MM-yyyy" how can you do it?
Use serializer to output to JSON and deserializer to set date to java property.

Serializer:
public class JsonDateSerializer extends JsonSerializer<Date> {

    /*
     * (non-Javadoc)
     *
     * @see org.codehaus.jackson.map.JsonSerializer#serialize(java.lang.Object,
     * org.codehaus.jackson.JsonGenerator,
     * org.codehaus.jackson.map.SerializerProvider)
     */
    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider prov) throws IOException, JsonProcessingException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        String fDate = dateFormat.format(date);
        gen.writeString(fDate);

    }

}

Deserizlizer:
public class JsonDateDeserializer extends JsonDeserializer<Date> {

    /*
     * (non-Javadoc)
     *
     * @see
     * org.codehaus.jackson.map.JsonDeserializer#deserialize(org.codehaus.jackson
     * .JsonParser, org.codehaus.jackson.map.DeserializationContext)
     */
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctx) throws IOException, JsonProcessingException {
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        String dt = jp.getText();
        if (dt == null || dt.trim().length() == 0) {
            return null;
        }
        Date date = null;
        try {
            date = fmt.parse(dt);
        } catch (ParseException e) {
            throw new IOException(e);
        }

        return date;
    }
}





Also in order to use your new classes annotate the java getters\settters:

public class Applicant{
private Date  birthDate;

@JsonSerialize(using = JsonDateSerializer.class)
public Date getBirthDate(){
 return birthDate;
}

 @JsonDeserialize(using = JsonDateDeserializer.class, as = Date.class)
public void setBirthDate(Date date){
this.birthDate = date;
}
}

Комментариев нет:

Отправить комментарий