JAXB annotations not working with Jackson message converter

时间:2017-06-15 09:45:27

标签: java xml spring jaxb jackson-dataformat-xml

I have a spring web project, where I have updated few jars, classpath has both JAXB and Jackson XML dataformat jars. I am trying to get expected XML output from my controller with Jackson XML message converter, but the JAXB annotations are not working. Can someone please help?

package-info.java

@XmlSchema(xmlns = { 
    @XmlNs(prefix = "ac", namespaceURI = "http://www.example.com/ABC") 
    })
package com.example;

UserDemographics.java

@XmlRootElement(name = "user-demographics", namespace = "http://www.example.com/ABC")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDemographics {

    @XmlElement(name = "demographic", namespace = "http://www.example.com/ABC")
    private Set<Demographic> demographics = new TreeSet<>();

    @XmlAttribute(name="user-id")
    private int userId;

    static class Demographic{
        private String key;
        private String value;

        @XmlAttribute(name = "name")
        public String getKey() { return key; }

        @XmlValue
        public String getValue() { return value; }
    }
}

Expected output Works when I explicitly set Jaxb2RootElementHttpMessageConverter

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ac:user-demographics xmlns:ac="http://www.example.com/ABC" user-id="2">
    <ac:demographic name="ADDRESS">Mall Road</ac:demographic>
    <ac:demographic name="COUNTRY">India</ac:demographic>
</ac:user-demographics>

Incorrect, with default message converters (Uses MappingJackson2XmlHttpMessageConverter)

<UserDemographics xmlns="">
    <demographic>
        <demographic><name>ADDRESS</name><value>Mall Road</value></demographic>
        <demographic><name>COUNTRY</name><value>India</value></demographic>
    </demographic>
</UserDemographics>

When I try to set AnnotationIntrospector using following code

@Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper xmlMapper = Jackson2ObjectMapperBuilder.xml().build();
    xmlMapper.setAnnotationIntrospector(
            AnnotationIntrospector.pair(
                    new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()), 
                    new JacksonAnnotationIntrospector()));
    converters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));
  }

I get following incorrect response

<user-demographics xmlns="" xmlns="http://www.example.com/ABC" user-id="2">
    <demographic xmlns:zdef2091338567="" zdef2091338567:name="ADDRESS">Mall Road</demographic>
    <demographic xmlns:zdef112980045="" zdef112980045:name="COUNTRY">India</demographic>
</user-demographics>

1 个答案:

答案 0 :(得分:1)

正如我所看到的,你有两个问题,一个是缺少包级别前缀而不是supported而另一个是错误的前缀,它可以是resolved,通过对xml mapper使用不同的底层stax库实现。

我没有看到最新版本2.8.7 xml databind lib的第二个问题,它默认为woodstox stax库。

如果可以选择xmlb2RootElementHttpMessageConverter,则可以随时将xml数据库库从类路径中删除为默认值。

部分注释尚未supported