Search before asking
- [x] I searched in the issues and found nothing similar.
Describe the bug
Using an object node API to put in arbitrary fields and values seems to ignore registered modules in the object mapper that produced it. As a result, calling toString()
, and toPrettyString()
on resulting node if it's of java.time
module even with com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
registered produces an com.fasterxml.jackson.databind.exc.InvalidDefinitionException
where it cannot represent an java.time.Instant
object.
Version Information
2.19.1
Reproduction
- Create a mapper instance
- Create an object node root
- put in an instant object on any key
- try to fetch the resulting json node and call
toString
or the likes on it.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
ObjectNode objectNode = mapper.createObjectNode();
objectNode.putPOJO("foo", Instant.ofEpochMilli(1L));
System.out.println(mapper.writeValueAsString(objectNode));
try {
System.out.println(objectNode.get("foo").toString());
}
catch (Throwable e) {
e.printStackTrace();
}
try {
System.out.println(objectNode.get("foo").toPrettyString());
}
catch (Throwable e) {
e.printStackTrace();
}
(throwing calls wrapped with try/catch)
reference repo https://github.com/Dragas/stringifying
Expected behavior
Calls to these functions does not throw.
Additional context
Not really relevant in day to day work, just weird to see an exception in the debugger as normal serialization works
Comment From: cowtowncoder
This is a limitation of JsonNode.toString()
(and toPrettyString()
) -- proper way to serialize JsonNode
is to use ObjectMapper
:
String str = mapper.writeValueAsString(node);
The reason for this is that JsonNode
instances do not have references to an ObjectMapper
and as such a default "vanilla" ObjectMapper
instance must be used for toString()
method.
Comment From: cowtowncoder
FWTW, ideas for improving error handling would be welcome -- I agree that the current behavior is not great; does not indicate the real problem.