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

Unexpected curly braces when calling writeStartObject() #595

Closed ian1dunn closed 1 year ago

ian1dunn commented 1 year ago

Version: 2.14.2

I am in the beginnings of creating a custom serializer for a class (the entire serializer needs to be custom made due to the nature of the application) and ran into the following issue where ToXmlGenerator.writeStartObject() and ToXmlGenerator.writeEndObject() write curly braces to the file instead of the expected root element.

Here is the serializer method override which uses the _initWithRootName() method from #216

    @Override
    public void serialize(Store store, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        ToXmlGenerator xmlGenerator = (ToXmlGenerator) jsonGenerator;
        _initWithRootName(xmlGenerator, new QName("root"));

        xmlGenerator.writeStartObject();
        xmlGenerator.writeStringField("test", "value");
        xmlGenerator.writeEndObject();
    }

Here is the output that results from serializing an instance of this class:

<?xml version='1.1' encoding='UTF-8'?>{<test>value</test>
}
ian1dunn commented 1 year ago

Several javadocs, github issues, stackoverflow pages, and source code files later, I realized this is actually an issue with the DefaultPrettyPrinter I was using. I realized PrettyPrinters are format-dependent and that an XmlPrettyPrinter exists.

To fix my code, all I had to do was update this snippet of my ObjectMapper initialization:

// PrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
PrettyPrinter prettyPrinter = new DefaultXmlPrettyPrinter();
objectMapper.setDefaultPrettyPrinter(prettyPrinter);

In the future, it might be a good idea to document more things like this because there really wasn't anything online about this. Maybe a quick start guide for custom serialization would be cool :)

pjfanning commented 1 year ago

@cowtowncoder I added a small section about DefaultXmlPrettyPrinter in https://github.com/FasterXML/jackson-dataformat-xml/wiki and created https://github.com/FasterXML/jackson-core/pull/1017

cowtowncoder commented 1 year ago

Some other notes: