I want to serialize a creation date of type java.time.LocalDateTime as String, when calling a spring-data-rest service. The field of the entity is annotated with DateTimeFormat(iso=ISO.DATE_TIME). I also registered a LocalData to String Converter in the Spring Configuration class.
@Override
@Bean
protected ConversionService neo4jConversionService() throws Exception {
ConversionService conversionService = super.neo4jConversionService();
ConverterRegistry registry = (ConverterRegistry) conversionService;
registry.removeConvertible(LocalDateTime.class, String.class);
registry.removeConvertible(String.class, LocalDateTime.class);
registry.addConverter(new DateToStringConverter());
registry.addConverter(new StringToDateConverter());
return conversionService;
}
private class DateToStringConverter implements Converter<LocalDateTime, String> {
@Override
public String convert(LocalDateTime source) {
return source.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
But the converter is not called and the creation date is serialized as a Json structure like this:
creationDate: {
dayOfYear: 337,
monthValue: 12,
hour: 10,
minute: 15,
second: 30,
nano: 0,
year: 2011,
month: "DECEMBER",
dayOfMonth: 3,
dayOfWeek: "SATURDAY",
chronology: {
id: "ISO",
calendarType: "iso8601"
}
This is the entity definition:
@NodeEntity
public class CmmnElement {}
public class Definitions extends CmmnElement {
@DateTimeFormat(iso = ISO.DATE_TIME)
private LocalDateTime creationDate;
}
The simple repository looks like this:
@RepositoryRestResource(collectionResourceRel="definitions", path="/definitions")
public interface DefinitionsRepository extends PagingAndSortingRepository<Definitions, Long>{}
The creationDate is created by LocalDateTime.parse() from this String "2011-12-03T10:15:30".
I have an example on github: https://github.com/gfinger/neo4j-tests/tree/master/neo-spring-test The Leaf class has a creationDate of type LocalDateTime. If you run mvn spring-boot:run the embedded Neoi4J DB gets initialized with a Leaf instance. A call to http://localhost:8080/leaf%7B?page,size,sort} shows the date as json structure.
How can I get back this String instead of the Json object?
Ok, sorry for the delay. I checked it and if you look into the Neo4j database in
target/cmmn.db
it shows that the date is correctly serialized as string.I think the issue is rather with the json-converters of spring-data-rest, which might not be configured for
LocalDateTime
.You have to add this as dependency:
Then the leaves are rendered as:
See: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring#customizing-the-jackson-objectmapper