jackson-databind
                                
                                 jackson-databind copied to clipboard
                                
                                    jackson-databind copied to clipboard
                            
                            
                            
                        Serializing and deserialing `null` when wrapping with root name
Search before asking
- [X] I searched in the issues and found nothing similar.
Describe the bug
Sometimes you care about the serialized json always beeing an object (not the string null even though it's valid JSON). I understand that in some cases, when passing a null value, you can't derive any sensible root name, so "null" is a good default (maybe you should be able to opt in to get an exception instead ? or use a generic name "data" or "result" but I guess you chose not to have a "default" root name?). But in some cases the root name is known, so the serializing should be possible ?
// both return "null" but could return "{\"Pojo\":null}" ?
// are there other cases when the root name is know ?
mapper.writer().withRootName("Pojo").writeValueAsString(null)
mapper.writerFor(Pojo.class).with(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(null)
// for now these throw exception but should work if the serialization is allowed ?
mapper.readerFor(Pojo.class).with(DeserializationFeature.UNWRAP_ROOT_VALUE).readValue("{\"Pojo\":null}")
mapper.reader().withRootName("Pojo").readValue("{\"Pojo\":null}", Pojo.class)
//   Exception com.fasterxml.jackson.databind.exc.MismatchedInputException:
//     Cannot deserialize value of type `Pojo` from Null value (token `JsonToken.VALUE_NULL`)
A workaround is to wrap the null in another object that is never null but it's less expressive ?
// is there a better way to do this ?
mapper.writeValueAsString(mapper.createObjectNode().putPOJO("Pojo", null));
// correctly returns "{\"Pojo\":null}"
mapper.treeToValue(mapper.readTree("{\"Pojo\":null}").get("Pojo"), Pojo.class)
// correctly returns null
Closely related, rootname or WRAP_ROOT_VALUE already works to guarantee that you get an object for almost all cases (numbers, strings, lists, ...), just not null ? Hence changing this would make it more useful ?
Obviously in real world use cases this code is working on something that is sometimes null sometimes nonnull.
Version Information
2.15.2