`@JsonRootName` 在与 POJONode 一起使用时被忽略

`@JsonRootName` ignored when used with POJONode

在处理遗留代码时,我创建了一个扩展 com.fasterxml.jackson.databind.node.POJONode 的包装器 class(我无法避免这一点)。

尽管我用 @JsonRootName 注释了包装器 class,但始终使用原始 class 名称进行序列化。看起来注释被完全忽略了。如果我使用 @JsonTypeName@JsonTypeInfo(我在周围的一些示例中找到),也会发生同样的情况。

我写了下面这个简单的JUnit测试,证​​明了这个问题:

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

实际结果

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

预期结果

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

在pom文件中,我添加了jackson-databindjackson-dataformat-xmljackson-module-jaxb-annotations的依赖,所有版本都是2.12.4(目前最新的)。

如果我做错了什么,请提出修复建议,或者可能的话,建议替代方案。再次强调一下,由于遗留代码,我有必要扩展 POJONode class。

非常感谢对此问题的任何帮助。

非常感谢您的宝贵时间和帮助。

如问题评论所述,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