LocalDateTime is not converted to String but to Json object

8.4k views Asked by At

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?

2

There are 2 answers

1
Michael Hunger On

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.

bin/neo4j-shell -path target/cmmn.db/

neo4j-sh (?)$ match (n) return *
> ;
+--------------------------------------------------------------------------------------+
| n                                                                                    |
+--------------------------------------------------------------------------------------+
| Node[0]{name:"Senat"}                                                                |
| Node[1]{name:"Cato",description:"Ceterum Censeo",creationDate:"2011-12-03T10:15:30"} |
+--------------------------------------------------------------------------------------+
2 rows

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:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>2.4.5</version>
    </dependency>

Then the leaves are rendered as:

  "name" : "Cato",
  "description" : "Ceterum Censeo",
  "creationDate" : "2011-12-03T10:15:30",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/leaf/7"
    }

See: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring#customizing-the-jackson-objectmapper

0
Keshav Varma On

I had similar problem in spring mvc. Adding dependency of jackson-datatype-jsr310 doesn't solved my problem instead Custom formatter did the job.

Here I found that https://stackoverflow.com/a/34548741/9091816

public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime>{
    private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    
    @Override
    public void serialize(LocalDateTime dateTime, JsonGenerator generator, SerializerProvider sp)
            throws IOException, JsonProcessingException {
        String formattedDateTime = dateTime.format(DateTimeFormatter.ofPattern(dateTimeFormat)); 
        generator.writeString( formattedDateTime);
    }
}

and use that custom serializer in your LocalDateTime field:

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