https://i.stack.imgur.com/aaPHR.png
I get date (udate field) in String format from API.
I have DTO class for this. But i need get day like '28.12.2021' for send to user.
public class CardHistoryUtrno {
@JsonDeserialize( using = MyDateDeserializer.class )
@JsonFormat(pattern="yyyyMMdd")
private Date udate;
Now i take date like this:
https://i.stack.imgur.com/I2oxj.png
MyDateDeserializer.class
public class MyDateDeserializer extends JsonDeserializer {
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
How i can get date like DD.MM.YYYY?
CodePudding user response:
public class MyDateDeserializer extends JsonDeserializer {
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String date2 = jsonParser.getText();
LocalDate localDate = LocalDate.parse(date2, formatter);
// LocalDate localDate1= LocalDate.parse(formatter2.format(localDate));
return localDate;
}
I do this and its working. Thanks)
CodePudding user response:
The JsonDeserializer
instructs Jackson how to convert a serialized input (in JSON) into an object (a Date
).
Specularly, you need to create a JsonSerializer
(and annotate the same field with it) in order to serialize the Date
object into the format you want. That would be:
public final class TimestampSerializer extends JsonSerializer<Date> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy");
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String str = DATE_TIME_FORMATTER.format(date);
jsonGenerator.writeString(str);
}
}
Suggestion: the class Date
is deprecated, prefer something newer such as LocalDate
(if you care about the time zone) or Instant
(if you want to leave everything at UTC timezone).