我正在尝试将对象映射到JSON。这很好,但我也希望在JSON中公开@Id
。我已经找到this如何做到这一点的答案,但为了使用该解决方案,我必须扩展RepositoryRestMvcConfiguration
。当我扩展它时,我的Java 8时间格式化正在破坏。我的JSON如下:
{"name":"erik",birthDate:"2015-01-01"}
birthDate字段是Java 8 LocalDate。现在,我还尝试通过扩展@Id
并设置RepositoryRestMvcConfiguration
来公开configuration.exposeIdsFor(MyClass.class);
。现在我公开了ID,但是,由于扩展RepositoryRestMvcConfiguration
,我的LocalDate
现已序列化为:
"birthDate":{"year":2015,"month":"AUGUST","chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfMonth":15,"dayOfWeek":"SATURDAY","era":"CE","dayOfYear":227,"leapYear":false,"monthValue":8}
所以,我的问题是:如何在保留LocalDate
格式的同时公开我的班级ID?
答案 0 :(得分:1)
听起来你正在遇到this Spring Boot issue中描述的问题。简而言之,问题是RepositoryRestMvcConfiguration
子类的存在导致使用Spring MVC的默认JSON转换器,而不是您配置的那个。如问题中所述,您可以通过在应用程序的配置中声明以下bean来解决此问题:
@Bean
public HttpMessageConverters httpMessageConverters(
final Jackson2ObjectMapperBuilder builder,
List<HttpMessageConverter<?>> converters) {
return new HttpMessageConverters(converters) {
@Override
protected List<HttpMessageConverter<?>> postProcessConverters(
List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
builder.configure(((MappingJackson2HttpMessageConverter) converter)
.getObjectMapper());
}
}
return converters;
}
};
}