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 ?
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;
Calendar
to JSONCreate 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;