0

I know there are several questions of the same topic but I don't think they quite cover my problem in a Spring Boot 2 application.

I have a model which uses LocalTimeDate. Getting this via rest api works fine, date is of the format "date":"2019-12-17T08:50:00"

I have created Serializer so that the json output is customised as there are reference fields that I do not want expanded.

The relevant code in the custom serialzer is

jgen.writeStringField("date", formatter.format(value.date));

with formatter as

private SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

I apply @JsonSerialize using the custom serialzer class to the model class. The result is

{"timestamp":"2019-12-25T10:57:50.482+0000","status":500,"error":"Internal Server Error","message":"Could not write JSON: Cannot format given Object as a Date; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Cannot format given Object as a Date (through reference chain: java.util.ArrayList[0])","path":"/api/v1/climates"}

I have used https://codeboje.de/jackson-java-8-datetime-handling/ as a guide and so updated the pom and application.properties and then allowed Spring to do its magic.

Is there something I have missed?

oguz ismail
  • 1
  • 16
  • 47
  • 69
John
  • 1,593
  • 3
  • 17
  • 28
  • 1
    SimpleDateFormat is an obsolete class, used to parse and format the obsolete java.util.Date class. Read the LocalDateTime javadoc to learn how to format a LocalDateTime. But simply using toString() will give you the standard, ISO format. – JB Nizet Dec 25 '19 at 11:17
  • I seriously doubt that you need any custom serializer. I solved a similar problem by using [jackson-modules-java8](https://github.com/FasterXML/jackson-modules-java8) and setting `WRITE_DATES_AS_TIMESTAMPS` to false. (And I agree that you should under all circumstances stay away from `SimpleDateFormat`.) – Ole V.V. Dec 25 '19 at 11:37
  • Related: [Java : Cannot format given Object as a Date](https://stackoverflow.com/questions/10649782/java-cannot-format-given-object-as-a-date) – Ole V.V. Dec 25 '19 at 11:39
  • 1
    Also, note that your "2019-12-25T10:57:50.482+0000" contains time-zone info which your format doesn't handle, also LocalDateTime does not relate to timezone. This may be a problem. Also, like others I strongly agree - DO NOT TOUCH SimpleDateFormat. See java.time.format.DateTimeFormatter class – Michael Gantman Dec 26 '19 at 13:17

2 Answers2

0

You need to use java.time.format.DateTimeFormatter. In your case:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

and you can use it in the same way as obsoleted SimpleDateFormat class.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
0

So eventually I went with

jgen.writeStringField("date", value.getDate().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

which worked.

John
  • 1,593
  • 3
  • 17
  • 28