Serialization for Java Calendar

Adarsh Gangaprakash Unnithan picture Adarsh Gangaprakash Unnithan · Nov 23, 2015 · Viewed 8.3k times · Source

How do I create a custom serialization for java Calendar to json by extending json serializer<Calendar>?

I tried the same for java.until.Date and it's working. In the serialization method, I converted Date as String and write it in json format.

The sample code done for java.util.Date is similar to code given below

  public class CDJsonDateSerializer extends JsonSerializer<Date>{
  @Override
  public void serialize(Date date, JsonGenerator jsonGenerator,SerializerProvider provider)
 throws IOException {

      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
      String dateString = dateFormat.format(date);
     jsonGenerator.writeString(dateString);
 }
}

And it is used like so:

 @JsonSerialize(using = CDJsonDateSerializer.class)
 private Date startDate;

What can I do for Serialize Calendar in java to json without losing data in Calendar object ?

Answer

cassiomolin picture cassiomolin · Nov 23, 2015

From JSON to Calendar

Create a JsonSerializer:

public class CalendarSerializer extends JsonSerializer<Calendar> {

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

    @Override
    public void serialize(Calendar calendar, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {

        String dateAsString = formatter.format(calendar.getTime());
        jsonGenerator.writeString(dateAsString);

    }
}

And then use it:

@JsonSerialize(using = CalendarSerializer.class)
private Calendar calendar;

From Calendar to JSON

Create a JsonDeserializer:

public class CalendarDeserializer extends JsonDeserializer<Calendar> {

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

    @Override
    public Calendar deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) 
                                throws IOException {

        String dateAsString = jsonParser.getText();

        try {
            Date date = formatter.parse(dateAsString);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

And then use it:

@JsonDeserialize(using = CalendarDeserializer.class)
private Calendar calendar;