Announcement Announcement Module
No announcement yet.
Date conversion when serializing from domain to JSON Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Date conversion when serializing from domain to JSON

    Given the following domain object:

    import java.util.Date;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.validation.constraints.NotNull;
    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.roo.addon.javabean.RooJavaBean;
    import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
    import org.springframework.roo.addon.json.RooJson;
    import org.springframework.roo.addon.tostring.RooToString;
    public class Person {
        private String name;
        private Integer age;
        private Integer size;
        @DateTimeFormat(style = "M-")
        private Date birthDate;
    when calling the ROO generated toJsonArray() method I get the following JSON String

    Any idea how to get formatted localized dates here?

    Thank you in advance
    Last edited by Fireball; Jan 20th, 2012, 09:18 AM.

  • #2
    I use JSON serialization annotations around my getter/setter methods.

    @JsonSerialize(using = JsonCalendarSerializer.class)
    public Calendar getExpirationDate() {
    return expirationDate;

    @JsonSerialize(using = JsonCalendarSerializer.class)
    public void setExpirationDate(Calendar expirationDate) {
    this.expirationDate = expirationDate;

    Then define the serializer (found elsewhere on web):

    * Used to serialize Java.util.Date, which is not a common <a target="_blank" title="JSON" href="">JSON</a>
    * type, so we have to create a custom serialize method;.
    * @author Loiane Groner
    * (English)
    * (Portuguese)
    public class JsonCalendarSerializer extends JsonSerializer<Calendar> {

    public static final String DATE_FORMAT = "yyyy-MM-dd";

    public void serialize(Calendar date, JsonGenerator gen, SerializerProvider provider)
    throws IOException, JsonProcessingException {
    SimpleDateFormat formatter = new SimpleDateFormat(JsonCalendarSerializer.DATE_FORMA T);
    String formattedDate = formatter.format(date.getTime());