我想在调用 spring-data-rest 服务时将 java.time.LocalDateTime 类型的创建日期序列化为字符串。实体的字段用 DateTimeFormat(iso=ISO.DATE_TIME) 注释。我还在 Spring Configuration 类中注册了一个 LocalData to String Converter。
@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);
}
}
但是转换器没有被调用,创建日期被序列化为这样的 Json 结构:
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"
}
这是实体定义:
@NodeEntity
public class CmmnElement {}
public class Definitions extends CmmnElement {
@DateTimeFormat(iso = ISO.DATE_TIME)
private LocalDateTime creationDate;
}
简单的存储库如下所示:
@RepositoryRestResource(collectionResourceRel="definitions", path="/definitions")
public interface DefinitionsRepository extends PagingAndSortingRepository<Definitions, Long>{}
creationDate 由 LocalDateTime.parse() 从这个字符串“2011-12-03T10:15:30”创建。
我在github上有一个例子:https://github.com/gfinger/neo4j-tests/tree/master/neo-spring-test Leaf 类有一个 LocalDateTime 类型的 creationDate。如果您运行 mvn spring-boot:run 嵌入式 Neoi4J DB 将使用 Leaf 实例进行初始化。调用 http://localhost:8080/leaf%7B?page,size,sort}将日期显示为 json 结构。
我怎样才能取回这个字符串而不是 Json 对象?
最佳答案
好的,抱歉耽搁了。
我检查了它,如果您查看 target/cmmn.db
中的 Neo4j 数据库,它会显示日期已正确序列化为字符串。
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
我认为问题出在 spring-data-rest 的 json 转换器上,它可能没有为 LocalDateTime
配置。
你必须添加这个作为依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.5</version>
</dependency>
然后叶子被渲染为:
"name" : "Cato",
"description" : "Ceterum Censeo",
"creationDate" : "2011-12-03T10:15:30",
"_links" : {
"self" : {
"href" : "http://localhost:8080/leaf/7"
}
关于spring - LocalDateTime 未转换为 String 而是转换为 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30866577/