0

I am trying to get an XML response from my CXF version 3.1 based REST service in java in the following format.

<root>
 <element a="X" b="1.2" c="3.2"/>
 <element a="Y" b="5.5" c="1.4"/>
 <element a="Z" b="54.2" c="55.4"/>
</root>

I have defined my DTO as below :

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="root")
public class Root{

    private List<Element> element;

    ---getters setters and no arg constructor--
}
@XmlType(propOrder = {
    "a","b","c"})
@XmlRootElement(name="element")
public class Element{

    @XmlAttribute
    private String a;

    @XmlAttribute
    private Double b;

    @XmlAttribute
    private Double c;

    ---Getter Setter---

}

I have not overriden any mapper, so default CXF JAXB xml mapper is in action.

But my xml response is coming as :-

<root>
   <element>
      <element>
          <a>X</a>
          <b>1.2</b>
          <c>3.2</c>
       </element>
       <element>
          <a>Y</a>
          <b>5.5</b>
          <c>1.4</c>
       </element>
       <element>
          <a>Z</a>
          <b>54.2</b>
          <c>55.4</c>
       </element>
    </element>
</root>

I have checked the Moxy API option as well, but that i cant use. Can someone please help that what is wrong with my code or what is missing ?

Thanks in advance

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Dhiraj
  • 1

1 Answers1

0

After spending quite some time, i found the problem and then figurred out the solution as well.

Problem

The problem was that apache cxf by default marshaller i.e. JAXB was not honouring the attribute annotations and hence was represnting the fields as elements instead of attributes.

Solution

Since by default serialization and de-serialization mechanism i.e. JAXB was not working hence we need to override this. And here my problem got solved by using Jackson as the serialization and de-serialization api.

Jackson starting with 2.0 verison provide both JSON as well as XML formats, and have exposed xml specific annotations for the same.

Use @JacksonXmlProperty with attribute set as true and then overriding the ObjectMapper bean as below solved the problem.

@Bean
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper= new ObjectMapper();
        //overriding apache cxf JAXB mapper to use jackson mapper.
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        objectMapper.setAnnotationIntrospector(introspector);
        return objectMapper;
Dhiraj
  • 1