I have Pojo as
public class Person
{
private String name;
@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate dob;
public Person()
{
}
public Person(String name, LocalDate dob)
{
this.name = name;
this.dob = dob;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public LocalDate getDob()
{
return dob;
}
public void setDob(LocalDate dob)
{
this.dob = dob;
}
}
When I tried to run code like
public static void main(String[] args) throws IOException{
Person person = new Person("Bob",new LocalDate(1900,02,22));
Gson gson = new Gson();
String json = gson.toJson(person);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Person returnPojo = mapper.readValue(json, Person.class);
System.out.print(returnPojo);
}
I keep get Exception as
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected START_ARRAY: expected JSON Array, String or Number at [Source: {"name":"Bob","dob":{"iLocalMillis":-2204496000000,"iChronology":{"iBase":{"iMinDaysInFirstWeek":4}}}}; line: 1, column: 14] (through reference chain: pojo.Person["dob"])
What have I done wrong?
You are writing JSON with Gson(which doesn't understand @JsonSerialize). Since the date is not in the right format, Jackson fails to read the date.
Try something like this:
Person person = new Person("Bob",new LocalDate(1900,02,22));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writer().writeValueAsString(person);
Person returnPojo = mapper.readValue(json, Person.class);
System.out.print(returnPojo);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.