2016-04-14 10 views
1

@JsonDeserialize注釈が機能しないときに問題が発生します。クライアントからの誕生日の値に "12.06.1999"が含まれている場合、400 Bad Request HTTPコードの応答が得られます。 @JsonSerialize注釈がうまく機能するので、私にとっては非常に奇妙な動作です!しかし、@JsonDeserializeの代わりに@DateTimeFormat注釈を使用すると、すべて動作します。@JsonDeserialize注釈が機能しない

私は、Java 8を使用して、私のコードがあります:

public class Person { 
    @JsonProperty("birthday") 
    @JsonSerialize(using = DateSerializer.class) 
    @JsonDeserialize(using = DateDeserializer.class) 
    private LocalDate birthday; 

    // other fields, getter and setter, etc. 
} 

public class DateSerializer extends JsonSerializer<LocalDate> { 
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); 

    @Override 
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) 
     throws IOException, JsonProcessingException { 
     generator.writeString(formatter.format(value)); 
    } 
} 

public class DateDeserializer extends JsonDeserializer<LocalDate>{ 

    @Override 
    public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException { 

     ObjectCodec oc = jp.getCodec(); 
     TextNode node = oc.readTree(jp); 
     String dateString = node.textValue(); 

     Instant instant = Instant.parse(dateString); 
     LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); 
     LocalDate date = LocalDate.of(dateTime.getYear(), dateTime.getMonth(), dateTime.getDayOfMonth()); 

     return date; 
    } 
} 

@RequestMapping(value = "/savePerson", method = RequestMethod.POST) 
@ResponseBody 
public Map<String, Object> savePerson(@ModelAttribute("person") Person person) 
{ 
    // a some code to save entity 
} 

にはどうすれば@JsonDeserializeを使用する必要がありますか?

+0

あなたはどのようにあなたがそれを解決したのを覚えていますか? – deadManN

答えて

0

のlog4jの設定は私をたくさん助けた: "= ALL log4j.category.org.springframework"

+0

:|それがあなたに言ったことを分かち合うことができますか? – deadManN

+0

それはずっと前だったので私は覚えていません。しかし、スタックトレースの例外があり、解決しました。 – Paul

+0

最後に私は春のブート時にlog4jを設定しましたが、Tomcatで実装しようとしたときに問題が発生しました:-s、アプリケーションが私のシリアライザクラスを入力します。 – deadManN

0

これはあなたの目的を果たすことがあります。

public class Person { 
    @JsonProperty("birthday") 
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="MM.dd.yyyy") 
    private LocalDate birthday; 

    // other fields, getter and setter, etc. 
} 
+0

私はまだエラーが発生します: "サーバーが400のステータス(Bad Request)で応答しました" – Paul

関連する問題