jackson-dataformat-xml icon indicating copy to clipboard operation
jackson-dataformat-xml copied to clipboard

Dollars in POJO property names are not escaped on serialization

Open mensinda opened this issue 3 years ago • 2 comments

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 avatar May 03 '22 13:05 mensinda

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.

mensinda avatar May 05 '22 12:05 mensinda

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.

cowtowncoder avatar May 07 '22 01:05 cowtowncoder