2017-10-29 3 views
0

OptionalJava 8でテストしており、serialize/deserializeLocalDateからJsonを入力したいと考えています。だから私は、私はJdk8Moduleを登録するカスタムObject Mapperを作成している:私はそれがスローすべてItemデータを取り、私のコントローラからGET方法を行う際にLocalDateを逆シリアル化するJdk8Moduleでオプションでエラーが発生する

public class Item implements Serializable{ 
    @JsonDeserialize(using = LocalDateDeserializer.class) 
    private LocalDate insertDate; 

    public Item(){} 

    public Item(LocalDate insertDate) { 
     this.insertDate = insertDate; 
    } 

    public Optional<LocalDate> getInsertDate() { 
     return Optional.ofNullable(insertDate); 
    } 
} 

しかし:

@Bean 
    public ObjectMapper objectMapperBuilder(){ 
     ObjectMapper objectMapper = new ObjectMapper(); 
     objectMapper.registerModule(new Jdk8Module()); 
     return objectMapper; 
    } 

そして、私のEntityクラスには、次のようになります。

Resolved exception caused by Handler execution: 
org.springframework.http.converter.HttpMessageNotWritableException: 
Could not write JSON: java.util.Optional cannot be cast to java.time.LocalDate; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
java.util.Optional cannot be cast to java.time.LocalDate(through reference chain: 
org.springframework.data.domain.PageImpl["content"] 
->java.util.Collections$UnmodifiableRandomAccessList[0] 
->com.inventory.models.Item["insertDate"]) 

コードを改善する方法やコードに追加すべき点それを動作させるには?

答えて

0

LocalDateのメンバを持っているがゲッタがOptional<LocalDate>であるため、エラー状態のような混乱が生じる可能性があります。

どちらか一方が間違っていますか?

私がしようとするだろう - 変更するexception-に基づく:

public Optional<LocalDate> getInsertDate() { 
    return Optional.ofNullable(insertDate); 
} 

public LocalDate getInsertDate() { 
    return Optional.ofNullable(insertDate).get(); 
} 

OR

変更

private LocalDate insertDate; 

へOprional

public setInsertDate(Optional<LocalDate> optLocalDate) { 
    this.localDate = optLocalDate.get(): 
} 
を受け付ける設定部を作成し、注釈及び/又はデシリアライザ

@JsonDeserialize(using = LocalDateDeserializer.class) 

OR

に交換が必要になる場合があります

private Optional<LocalDate> insertDate; 

関連する問題