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 ?
The DateFormat class in Java is used for formatting dates. A specified date can be formatted into the Data/Time string. For example, a date can be formatted into: mm/dd/yyyy.
util. Calendar: It is an abstract class that provides methods for converting between instances and manipulating the calendar fields in different ways.
The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With