0

I need to set a specific format for any serialized LocalTime with jackson.

It works fine with @JsonFormat, but this is only valid for specific properties and not for all serialized with ObjectMapper. Besides, I use a custom BeanSerializerModifier and it doesn't seem to recognize the properties marked with @JsonFormat.

I can do it for dates using ObjectMapper.setDateFormat, however, there doesn't seem to be a method like it for times. Is there any easy way of doing it?

Haf
  • 375
  • 1
  • 3
  • 13
  • Does this help you https://stackoverflow.com/questions/12463049/date-format-mapping-to-json-jackson :) – JCompetence Aug 20 '21 at 11:20
  • I wish! I need a `HHmm` format and tried with `mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HHmm"));` but this is ignored when serializing `LocalTime` objects – Haf Aug 20 '21 at 11:35
  • This should help https://stackoverflow.com/questions/27952472/serialize-deserialize-java-8-java-time-with-jackson-json-mapper – JCompetence Aug 20 '21 at 11:42
  • Seems like most of these answers are suggesting to use the `JavaTime` module, but I'm already using it so it doesn't help. The other solution is using a custom serializator which I've also considered (I'd have to use it in my `BeanSerializerModifier`) but this seems a bit overkill, I mean, it's pretty easy for dates, so why not for times? – Haf Aug 20 '21 at 11:51
  • I had a similar problem a few years ago, maybe this helps: https://stackoverflow.com/questions/40487656/jackson-java-time-iso-8601-serialize-without-milliseconds – Benjamin M Aug 20 '21 at 13:42
  • @BenjaminM really good! This works! Although I'm still wondering if there's something simpler – Haf Aug 20 '21 at 13:56
  • @G9QV2 The answers there provide some alternatives, for example using `@JsonFormat`, but that's of course not global. Else I'd say: Just go for it. 5 lines of code you can put in some "config" class and silently ignore – Benjamin M Aug 20 '21 at 14:01

0 Answers0