0

I have a class that represent data in which there is LocalDate field.

public class Student {
    private String name;
    private LocalDate dob;
    //getters and setters
}

In pom.xml I have jackson-modules-java8 so that LocalDate could be deserialized. I'm having difficulty preparing correct JSON to be able to send POST. Here it is:

{ "name" : "John", "dob" : [ 1986::10::06 ] }

In a response to POST I get Cannot deserialize instance ofjava.time.LocalDateout of START_ARRAY token. Decorating the field dob with annotation @JsonFormat(pattern = "yyyy::MM::dd") didnn't work. Three years ago workaround was published but things may have changed since then.

menteith
  • 596
  • 14
  • 51

2 Answers2

0

From the w3school description of json values:

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

According this definition your json is not valid because [1986::10::06] is not a valid value. You need to treat it as a string, adding the " characters around it instead of squared brackets.

The right json must be

{ "name" : "John", "dob" : "1986::10::06" }
Community
  • 1
  • 1
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • This time I'm getting `Cannot deserialize instance of `java.time.LocalDate` out of START_ARRAY token`. – menteith Mar 27 '18 at 10:42
  • You are right. That happens because your date field is not an array. It is necessary to remove the square brackets. Check updated answer – Davide Lorenzo MARINO Mar 27 '18 at 10:44
  • Stil no luck. I'm getting `Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('1986::10::06')` – menteith Mar 27 '18 at 10:48
  • @menteith that happens because there is no default constructor (a constructor without parameters) for LocalDate. You need to use a custom serializer deserializer to handle such kind of objects. – Davide Lorenzo MARINO Mar 27 '18 at 10:52
  • I cannot find an easy guide to writing custom deserializer. Could you link to some examples? – menteith Mar 27 '18 at 14:13
0

The LocalDate API doc says:

A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.

So you JSON should be like:

{ "name" : "John", "dob" : "1986-10-06" }
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
  • I'm getting `Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('1986-10-06')`. – menteith Mar 27 '18 at 10:44