Jackson Date Serialize and Deserialize with UTC+0 format and UTC+4

public class JacksonConfig {

private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);

@Override
public Class<LocalDateTime> handledType() {
return LocalDateTime.class;
}

@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException {
LocalDateTime dateTime = LocalDateTime.parse(parser.getText(), DATE_TIME_FORMATTER);
return dateTime.atZone(ZoneId.of("UTC"))
.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}

}

public static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);

@Override
public Class<LocalDateTime> handledType() {
return LocalDateTime.class;
}

@Override
public void serialize(LocalDateTime value,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException {
LocalDateTime utcDateTime =
value.atZone(ZoneId.systemDefault())
.withZoneSameInstant(ZoneOffset.UTC)
.toLocalDateTime();
jsonGenerator.writeString(DATE_TIME_FORMATTER.format(utcDateTime));
}

}

} 


Let's say we want to return date with UTC+0 format to frontend, which is in UTC+4 format in service. For this case we have to serialize date with UTC+0 format, and deserialize with. UTC+4 format when we receive this parameter again.

For this purpose we can create this config and annotated parameter with @JsonSerialize annotation

in request class:

(Request obj maybe date or string type for this case implementation maybe a little bit different for deserialize)

@JsonDeserialize(using = JacksonConfig.CustomLocalDateTimeDeserializer.class)
private LocalDateTime beginDate;

in response class:

@JsonSerialize(using = JacksonConfig.CustomLocalDateTimeSerializer.class)
private LocalDateTime beginDate;

Comments

Popular posts from this blog

Installation instructions for some programs on linux ubuntu

Hibernate and Application Performance

timezone ile bagli Jackson deserializableda problem