我能够使用默认映射器配置使用@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包括:
顺便说一句,我也尝试用这个配置XmlMapper:
xmlMapper.getSerializationConfig().with(new JaxbAnnotationIntrospector(xmlMapper.getTypeFactory()));
但由于根元素名称不正确,导致输出更差:<ProblemJaxb xmlns=""><id>aaa</id><description>test</description></ProblemJaxb>
答案 0 :(得分:2)
看起来这个问题存在before,但杰克逊的作者无法重现。好像臭虫报告似乎没有走得太远。
我能够使用XmlJaxbAnnotationIntrospector
代替JaxbAnnotationIntrospector
来解决问题。