2016-08-18 89 views
0

在我们的项目中,我们使用spring data rest(MongoDB)。 文件:转换LocalDateTime字段

@Document(collection = "brands") 
@Data 
@Accessors(chain = true) 
public class BrandDocument { 
    @Id 
    private String id; 

    @CreatedDate 
    private LocalDateTime createdDate; 

    @LastModifiedDate 
    private LocalDateTime lastModifiedDate; 

    private String name; 
    private Set<String> variants; 
} 

配置:

@SpringBootApplication 
@EnableDiscoveryClient 
@EnableMongoAuditing 
public class DictionaryService extends RepositoryRestConfigurerAdapter { 
    public static void main(String[] args) { 
     SpringApplication.run(new Object[]{ DictionaryService.class }, args); 
    } 

    @Override 
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { 
     config.exposeIdsFor(BrandDocument.class); 
    } 
} 

如果我试图让BrandDocument:

curl -X GET -H "Cache-Control: no-cache" -H "Postman-Token: c12dbb65-e173-7ff3-2187-bdb6adbdebe9" "http://localhost:7090/typeDocuments/" 

我会看到答案:

{ 
... 
    "lastModifiedDate": { 
     "content": "2016-08-10T15:50:05.609" 
    } 
... 
} 

在gradle这个DEPS我有为转换ja VA 8 LocalDateTime:

compile  group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310' 

如果我试图保存对象,发送POST请求http://localhost:7090/typeDocuments/与内容:

{ 
    ... 
     "lastModifiedDate": { 
      "content": "2016-08-10T15:50:05.609" 
     } 
    ... 
} 

我有转换错误,但如果:

{ 
... 
"lastModifiedDate": "2016-08-10T15:50:05.609" 
... 
} 

保存OK 。

为什么jackson为“lastModifiedDate”添加“content”字段?我该如何改变它?

回答

0

您是否在指定的位置指定要使用来自jackson-datatype-jsr310的串行器/解串器的杰克逊的ObjectMapper?如果没有,你必须做这样的:

@Configuration 
public class JacksonConfig { 

    @Bean 
    @Primary 
    public ObjectMapper objectMapper() { 
     ObjectMapper mapper = new ObjectMapper(); 
     mapper.registerModules(new JavaTimeModule()); 
     return mapper; 
    } 
} 
+0

如果使用你的对象映射它并没有帮助:( – maksaimer

+0

你调试 –

0

我有同样的问题,它原来是一个春天开机/春天的数据问题,而不是杰克逊。

弹簧数据扫描数据类并检测类型为LocalDateTime的字段。此类未注册为“简单类型”,因此在序列化之前将其转换为PersistentEntityResource(字段名为content)。这就是content的来源。

的解决方法是登记所有JSR-310类型为simpe类型:

@Bean 
public MongoMappingContext mongoMappingContext() { 
    MongoMappingContext context = new MongoMappingContext(); 
    context.setSimpleTypeHolder(new SimpleTypeHolder(new HashSet<>(Arrays.asList(
      Instant.class, 
      LocalDateTime.class, 
      LocalDate.class, 
      LocalTime.class, 
      MonthDay.class, 
      OffsetDateTime.class, 
      OffsetTime.class, 
      Period.class, 
      Year.class, 
      YearMonth.class, 
      ZonedDateTime.class, 
      ZoneId.class, 
      ZoneOffset.class 
    )), MongoSimpleTypes.HOLDER)); 
    return context; 
} 
+0

我刚才看到它的固定在spring-boot-1.4.1.RELEASE,尽管如此还是有问题:https://jira.spring.io/browse/DATAMONGO-1498 –

相关问题