I have a JSON String and I am using Jackson to parse it into a POJO. The incoming JSON string has a different format, so I had to write my own converter to convert the String to LocalTimeDate
object. I use 2 annotations to achieve this.
public class Content {
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@TDateFormat
private LocalDateTime modifiedDate;
}
TDateFormat: This annotation specifies the date format we need. It also has a default value.
@Retention(RetentionPolicy.RUNTIME)
public @interface TDateFormat {
String value() default "MMM d, yyyy, hh:mm:ss a";
}
LocalDateTimeDeserializer: This holds the logic to deserialize. We use the TDateFormat value get the format to use. I have extracted the logic out to an Util class
@NoArgsConstructor
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> implements ContextualDeserializer {
private String format;
public LocalDateTimeDeserializer(String format) {
this.format = format;
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext dc, BeanProperty bp) {
return new LocalDateTimeDeserializer(bp.getAnnotation(TDateFormat.class).value());
}
@Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
LocalDateTime localDateTime = Utils.convertDate(jp.getText(), format);
System.out.println("Done::: " + localDateTime);
return localDateTime;
}
}
The above code works fine. Now, I am trying to combine @TDateFormat
and @JsonDeserialize(using = LocalDateTimeDeserializer.class)
to @TDeserializer
@TDeserializer Looks like below.
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@TDateFormat
public @interface TDeserializer {
}
And I want to use the annotation like this
public class Content {
@TDeserializer
private LocalDateTime modifiedDate;
}
But I get the following error, when I make this little change.
2022-09-29 23:32:09.569 ERROR 90506 --- [ntainer#0-0-C-1] c.t.k.service.impl.KafkaMessageConsumer : Exception occurred::: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
at [Source: (String)"{"modifiedDate":"Sep 29, 2022, 11:25:56 PM" [truncated 149 chars]; line: 1, column: 52] (through reference chain: com.techopact.kafkautil.model.Article["modifiedDate"])
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
Can anyone please let me know what more I have to do to combine the annotations?