我能够使用默认映射器配置使用@JacksonXmlProperty注释生成我想要的XML . 但是我的类是由maven-jaxb2-plugin生成的,并且已经有了@XmlAttribute注释 . 当我尝试使用JaxbAnnotationIntrospector时,它将属性序列化为子元素 . 我究竟做错了什么?
预期输出: <problem xmlns="" id="aaa"><description>test</description></problem>
(可与testGenerateXmlCorrect一起重复)
实际输出: <problem xmlns=""><id>aaa</id><description>test</description></problem>
(可与testGenerateXmlWrong重复)
我也可以使用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));
}
}
Classpath包括:
-
com.fasterxml.jackson.core:jackson-core:jar:2.3.2
-
com.fasterxml.jackson.core:jackson-annotations:jar:2.3.2
-
com.fasterxml.jackson.core:jackson-databind:jar:2.3.2
-
com.fasterxml.jackson.dataformat:jackson-dataformat-xml:jar:2.3.2
-
com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.3.2
-
org.codehaus.woodstox:stax2-api:jar:3.1.1
-
javax.xml.stream:stax-api:jar:1.0-2
-
com.sun.xml.bind:jaxb-impl:jar:2.2.7
-
com.sun.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 回答
看起来这个问题存在于before,但 Jackson 的作者无法重现 . 似乎错误报告不是很远 .
我能够通过使用XmlJaxbAnnotationIntrospector而不是
JaxbAnnotationIntrospector
来解决问题 .