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

@JsonRootName doesn't work with POJONode

Open marcotizzano opened this issue 4 years ago • 2 comments

Hello everyone.

The issue starts from the need of converting an object from an XML format to a com.fasterxml.jackson.databind.JsonNode instance and serialize it with a Wrapper object.

I have created a wrapper class which extends com.fasterxml.jackson.databind.node.POJONode.

Despite I have annotated the wrapper class with @JsonRootName, that is always serialized with the original class name. It looks like that the annotation is totally ignored. The same happens if I use @JsonTypeName and @JsonTypeInfo.

If I am doing something wrong please suggest a fix or, possibly, an alternative. Because of legacy code, it is necessary for me to use POJONode class.

Thank you for your time and help. Marco Tizzano.

Version information I am currently using version 2.12.4 of jackson-databind, jackson-dataformat-xml and jackson-module-jaxb-annotations.

To Reproduce I have written the following simple JUnit test, which proves the issue:

import static java.lang.String.format;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.POJONode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class POJONodeJsonRootNameTest {

    static final String XML_PRE_PTRN = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>%s";

    private final ObjectMapper mapper = new ObjectMapper();

    private final XmlMapper xmlMapper = new XmlMapper();

    @Test
    public void shouldConvertObjectFromXmlToJson() throws IOException {

        String xml = format(XML_PRE_PTRN, "<test><name>test</name><description>test</description></test>");

        JsonNode node = xmlMapper.readTree(xml);

        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

        String json = mapper.writeValueAsString(new TestWrapper(node));

        assertNotNull(json);
    }

    @JsonRootName(value = "test")
    private class TestWrapper extends POJONode {

        public TestWrapper(Object v) {
            super(v);
        }
    }
}

Actual Result {"TestWrapper":{"name":"test","description":"test"}}

Expected behavior {"test":{"name":"test","description":"test"}}

marcotizzano avatar Aug 01 '21 02:08 marcotizzano

Hi After an additional investigation, I figured out that it all works fine up until version 2.10.5, then you get the bug with later versions. Hope that helps. Your answer on this matter would be highly appreciated. Thanks.

marcotizzano avatar Aug 02 '21 19:08 marcotizzano

Will transfer to correct repo.

cowtowncoder avatar Aug 17 '21 20:08 cowtowncoder