FasterXML / jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Apache License 2.0
400 stars 116 forks source link

*Serializer ignores format pattern if nano-second serialization enabled #248

Closed Sam-Kruglov closed 2 years ago

Sam-Kruglov commented 2 years ago

Copying from the previous issue #224

The following example has been fixed but you can try replacing Duration with Instant or any other temporal type to check if the issue reproduces or not:

class MyDto {
  @JsonFormat(pattern = "MINUTES")
  @JsonProperty("durationInMins")
  private final Duration duration;

  public MyDto(Duration d) { duration = d; }

  public Duration getDuration() { return duration; }
}

var mapper = new ObjectMapper().findAndRegisterModules();
Map<String, Object> map = mapper.convertValue(new MyDto(Duration.ofHours(2)), new TypeReference<>(){});
assertEqual(map.get("durationInMins"), 120);

Originally posted by @Sam-Kruglov in https://github.com/FasterXML/jackson-modules-java8/issues/224#issuecomment-882194448

cowtowncoder commented 2 years ago

Thank you @Sam-Kruglov. Actually I was looking for specific cases. I think I can leave this open as a placeholder to include known cases to fix.

But one quick note: handling of Duration (and other types) as Map keys requires more work since key serializers are different from value serializers -- and there is no current support for configuration via @JsonFormat.

Actually since the test above specifically tests as-Map-key serialization, I will change the title as well.

cowtowncoder commented 2 years ago

Hmmh. Does that code actually work? This:

new TypeReference<>(){}

should be illegal as it has no type information.

EDIT: I was mistaken, see Sam's comment below.

Sam-Kruglov commented 2 years ago

@cowtowncoder hey, I don't actually remember what I meant by Instant having similar issues, I just tried to poke around it and couldn't find anything, the pattern seems to work fine.

Also, the above example compiles and runs on JDK 11 with no problems, maybe you tried JDK 8? Yes, I can use diamond notation in the type reference as it fills the type in from the declaration. And the example is serializing duration in values, not in keys.

Thanks for looking into it!

cowtowncoder commented 2 years ago

@Sam-Kruglov Ok yes, I do build with Java 8. Good to know it might actually work later on. Should have thought this might be it. Learned something new :-)

Also yeah, I can see that Map was solely for convenience of testing. But it did get me thinking into "Duration as Map key" which is actually another missing piece of functionality. But you are right, that's not what test did.

And I think there may well still be issues for maybe other types so we can open issues once they are encountered.

Same goes for Duration-as-Map-key (and others).