Skip to content

Commit

Permalink
fix(track): dates are serialized as integer array instead of iso string
Browse files Browse the repository at this point in the history
  • Loading branch information
denniseffing committed Jan 3, 2024
1 parent cf2ecb5 commit f451e1a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package de.codecentric.habitcentric.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.kafka.support.JacksonUtils;
import org.springframework.kafka.support.serializer.JsonSerializer;

/**
* Custom Spring Kafka {@link JsonSerializer} that serializes timestamps as strings instead of
* integer arrays.
*
* <p>For some reason, Spring Boot does not use the auto-configured {@link ObjectMapper} when
* auto-configuring Spring Kafka. Instead, it calls the no-args constructor of the {@link
* JsonSerializer} class provided by the property {@code spring.kafka.producer.value-serializer}.
*
* @param <T>
* @see <a
* href="https://github.com/spring-projects/spring-kafka/issues/680">https://github.com/spring-projects/spring-kafka/issues/680</a>
* @see <a
* href="https://docs.spring.io/spring-kafka/reference/tips.html#tip-json">https://docs.spring.io/spring-kafka/reference/tips.html#tip-json</a>
*/
public class CustomJsonSerializer<T> extends JsonSerializer<T> {

public CustomJsonSerializer() {
super(createMapper());
}

private static ObjectMapper createMapper() {
var mapper = JacksonUtils.enhancedObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return mapper;
}
}
2 changes: 2 additions & 0 deletions services/track/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ spring:
flyway.schemas: hc_track
jackson:
serialization:
WRITE_DATES_AS_TIMESTAMPS: false
FAIL_ON_EMPTY_BEANS: false
jpa:
database-platform: postgres
Expand All @@ -36,6 +37,7 @@ spring:
producer:
properties:
"spring.json.type.mapping": "date-tracked:de.codecentric.habitcentric.track.habit.HabitTracking$DateTracked,date-untracked:de.codecentric.habitcentric.track.habit.HabitTracking$DateUntracked"
value-serializer: de.codecentric.habitcentric.track.CustomJsonSerializer

server:
port: 9002
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package de.codecentric.habitcentric.track;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class CustomJsonSerializerTest {

@Test
void creates() {
try (var subject = new CustomJsonSerializer<>()) {
assertThat(subject).isNotNull();
}
}
}

0 comments on commit f451e1a

Please sign in to comment.