有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确使用Jackson的JaxbAnnotationIntrospector?

我能够使用@JacksonXmlProperty注释和默认映射器配置生成我想要的XML。但我的类是由maven-jaxb2-plugin生成的,并且已经有@xmltattribute注释。当我尝试使用JaxbAnnotationIntrospector时,它将属性序列化为子元素。我做错了什么

预期输出:<problem xmlns="" id="aaa"><description>test</description></problem>(可通过testGenerateXmlCorrect重复)

实际输出:<problem xmlns=""><id>aaa</id><description>test</description></problem>(可与TestGenerateXmlError重复)

我还可以使用JAXB生成预期的XML,但问题是如何使用JaxbAnnotationIntrospector与Jackson一起生成

Junit测试:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Test;

public class JaxbAttributeTest {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JaxbAttributeTest.class);

@XmlRootElement(name="problem")
public static class ProblemJaxb {
    @XmlAttribute(name="id")     
    public String id;
    public String description;
}

@Test
public void testGenerateXmlWrong() throws JsonProcessingException {
    ProblemJaxb problem = new ProblemJaxb();
    problem.id = "aaa";
    problem.description = "test";
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(xmlMapper.getTypeFactory()));
    log.debug("ProblemJaxb: {}", xmlMapper.writeValueAsString(problem)); 
}

@JacksonXmlRootElement(localName="problem")
public static class ProblemJackson {
    @JacksonXmlProperty(isAttribute=true)
    public String id;
    public String description;
}

@Test
public void testGenerateXmlCorrect() throws JsonProcessingException {
    ProblemJackson problem = new ProblemJackson();
    problem.id = "aaa";
    problem.description = "test";
    XmlMapper xmlMapper = new XmlMapper();
    log.debug("ProblemJackson: {}", xmlMapper.writeValueAsString(problem));
}

}

类路径包括:

  • com。fasterxml。杰克逊。core:jackson core:jar:2.3.2
  • com。fasterxml。杰克逊。核心:jackson注释:jar:2.3.2
  • com。fasterxml。杰克逊。核心:jackson数据绑定:jar:2.3.2
  • com。fasterxml。杰克逊。dataformat:jackson dataformat xml:jar:2.3.2
  • com。fasterxml。杰克逊。模块:jackson模块jaxb注释:jar:2.3.2
  • 组织。科德豪斯。woodstox:stax2 api:jar:3.1.1
  • javax。xml。流:staxapi:jar:1.0-2
  • com。太阳xml。bind:jaxb impl:jar:2.2.7
  • com。太阳xml。bind:jaxb-core:jar:2.2.7
  • javax。xml。bind:jaxb-api:jar:2.2.7

顺便说一句,我还尝试使用以下配置XmlMapper:

xmlMapper.getSerializationConfig().with(new JaxbAnnotationIntrospector(xmlMapper.getTypeFactory()));

但这产生了更糟糕的输出,因为根元素名称不正确:<ProblemJaxb xmlns=""><id>aaa</id><description>test</description></ProblemJaxb>


共 (1) 个答案

  1. # 1 楼答案

    看起来这个问题是存在的,但杰克逊的作家们无法重现。看来bug报告并没有走得太远

    我用^{}而不是JaxbAnnotationIntrospector解决了这个问题