2016-08-18 55 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 –

相關問題