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
562 stars 221 forks source link

Dollars in POJO property names are not escaped on serialization #524

Closed mensinda closed 1 year ago

mensinda commented 2 years ago

Example:

package it;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class Dollar {

    public static class DTO {
        public String thisStringIs$Fancy$ = "Hello World!";
    }

    public static void main(String ... args) throws JsonProcessingException {
        DTO dto = new DTO();

        XmlMapper mapper = new XmlMapper();

        final String res = mapper.writeValueAsString(dto);

        // <DTO><thisStringIs$Fancy$>Hello World!</thisStringIs$Fancy$></DTO>
        System.out.println(res);

        // ERROR!
        // com.fasterxml.jackson.core.JsonParseException: Unexpected character '$' (code 36) excepted space, or '>' or "/>"
        mapper.readValue(res, DTO.class);
    }

}

jackson version: 2.13.2

mensinda commented 2 years ago

Workaround: Use ObjectMapper.setPropertyNamingStrategy() with something like this:

public class XmlNamingStrategy extends PropertyNamingStrategies.NamingBase {
    @Override
    public String translate(String propertyName) {
        return propertyName.replace("$", "_-_DOLLAR_-_");
    }
}

Still, this should work out of the box, or the XML generation should fail and not produce a broken XML string.

cowtowncoder commented 2 years ago

I think that providing a default PropertyNamingStrategy that is configured for XmlMapper (but may be replaced) is probably a good way to improve things. I thought we already had name mangling for POJO properties but turns out name mangling is currently only used for Type Ids of polymorphic type handling.

So this is something worth adding to 2.14 -- I hope to get it, or, if you or anyone else has time, could help with getting a PR merged.