2

I am trying to send some information with Kafka. I have a class to handle this task. The class includes a private variable called "timestamp" of type Instant. When the timestamp is generated, it renders correctly. However, when I receive the message on the consumer side, the time stamp is not readable.

It looks like this "timestamp": 1685968244.889278400

Additionally, I have a response class defined as follows:

public class Response<T> {
    private T data;
    private String statusCode;
    private String statusMessage;
    private Instant timestamp;
}

When I converted timestamp atribute to String, everything looks well but I want to render the timestamp as below:
"timestamp": 2023-06-05T15:07:06.497159Z How can I do that ?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
User
  • 58
  • 7
  • Does this answer your question? [converting epoch to ZonedDateTime in Java](https://stackoverflow.com/questions/47975195/converting-epoch-to-zoneddatetime-in-java) – Ole V.V. Jun 06 '23 at 15:27
  • Try to add this dependency on both sides: `com.fasterxml.jackson.datatype:jackson-modules-java8`. So, Jackson will serialize and deserialiaze Java time objects properly: https://learnersbucket.com/examples/java/serialize-deserialize-java-8-java-time-with-jackson-json-mapper/ – Artem Bilan Jun 06 '23 at 16:45
  • @OleV.V. unfortunately that's not the answer for me – User Jun 07 '23 at 06:08
  • @ArtemBilan this dependency already included but when I use that dependency for deserialize, the API is failing. Therefore, I need to use `JsonDeserializer` from `org.springframework.kafka.support.serializer.JsonDeserializer` – User Jun 07 '23 at 06:10
  • So, does it work or not? That `JsonDeserializer` relies on a `JacksonUtils.enhancedObjectMapper()` by default which does this `registerWellKnownModulesIfAvailable(objectMapper);` including the mentioned `com.fasterxml.jackson.datatype.jsr310.JavaTimeModule`. Therefore I'm not sure in your comment. – Artem Bilan Jun 07 '23 at 12:50
  • @ArtemBilan Sorry for confusing. When I use `JsonDeserializer` from `org.springframework.kafka.support.serializer.JsonDeserializer` API is able to run but the output is like this: `"timestamp": 1685968244.889278400`. When I use `JsonDeserializer` from `com.fasterxml.jackson` even API is not able to run. It's failing while API is building – User Jun 08 '23 at 06:38
  • That's correct. We talk exactly about `org.springframework.kafka.support.serializer.JsonDeserializer`. That dependency must be there as well. – Artem Bilan Jun 08 '23 at 13:02

1 Answers1

2

I suspect from Instant type. Once, I had the same problem and I fixed that when I replace Instant with DateTime from Joda-Time. Another possible solution is if you are using a custom serializer/deserializer that might occur too. So, basically, you can use JsonSerializer/JsonDeserializer. I wish this information will work for you

Serdar
  • 146
  • 8