Search code examples
javajsonjacksonjackson-databind

`@JsonRootName` ignored when used with POJONode


While working on legacy code, I have created a wrapper class which extends com.fasterxml.jackson.databind.node.POJONode (I cannot avoid this).

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 (which I found in some example around).

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));

        System.out.println(json);

        assertNotNull(json);
    }

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

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

Actual result

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

Expected Result

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

In the pom file, I have added dependecies of jackson-databind, jackson-dataformat-xml and jackson-module-jaxb-annotations, all version 2.12.4 (currently the latest one).

If I am doing something wrong please suggest a fix or, possibly, an alternative. Again, let me stress out, it is necessary for me to extend POJONode class, due to legacy code.

Any help on this issue would be highly appreciated.

Thank you very much for your time and help.


Solution

  • As said in the comments to the question, Marco Tizzano 's code works fine up until jackson 2.10.5 version. This would suggest that after this version a regression issue had been included and appeared again in the latest jackson 2.12.4 version released in the month of July 2021. Marco Tizzano reported the issue to the developers on the FasterXml issue tracker : the link with the complete description of the issue is here.