FasterXML / jackson-dataformat-xml

Extension for Jackson JSON processor that adds support for serializing POJOs as XML (and deserializing from XML) as an alternative to JSON
Apache License 2.0
574 stars 222 forks source link

Feature request: subclasses of ObjectMapper to override all methods that return "this" to allow fluent chaining #675

Closed djechelon closed 1 month ago

djechelon commented 1 month ago

Very simple feature request.

The following code does not work with XmlMapper as it is written, and fluent chaining is a way to make code more readable

private static final ObjectMapper XML_MAPPER = new XmlMapper()
        .configure(WRITE_XML_DECLARATION, false)
        .configure(WRITE_XML_1_1, false)
        .configure(WRITE_NULLS_AS_XSI_NIL, false)
        .configure(UNWRAP_ROOT_OBJECT_NODE, true)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL)
        .registerModule(new JakartaXmlBindAnnotationModule())        
;

The reason is extremely simple: XmlMapper, as other Mappers (e.g. Yaml) extend ObjectMapper, and while they return this, their signature reports the superclass ObjectMapper.

Now, if I want to extend the discussion to programming theories, I would suggest that JLS is changed to allow for a particular "this" return type, bla bla bla.

But, let's be realistic and currentl my suggestion is to override all methods in the extended classes that simply invoke the superclass in order to add the extended type to the return type.

E.g.

@Override
public XmlMapper configure(Feature f, boolean state) {
    super.configure(f, state);
    return this;
}

For all methods..... obviously....

I could create the PR personally if this is of interest

pjfanning commented 1 month ago

maybe on master but this would be a breaking change if applied on a 2.x branch

cowtowncoder commented 1 month ago

Unfortunately can not be done for 2.x: this is binary-incompatible change and would cause wide-spread breakage.

And in 3.0 mappers are immutable, using Builders which have full chaining support. So not needed for master.

However: 2.18.0 (actually probably 2.10+) already has support for Builders so you can change your code to something like:

XmlMapper mapper = XmlMapper.builder()
   .configure( ... )
   ...
   .build();