0

I'm new to Jackson XML and I have a requirement of constructing a Jackson XML with different element name and attributes but under same root element.

My Expected xml output

<item name="Whatever">
 <problem_id id="12312"/>
 <problem_type type="1765"/>
 <problem_desc desc="faulty"/>
 </item>

My pojo class ( Not sure how to add the remaining elements and attributes)

@JacksonXmlRootElement(localName = "item")
public class ItemsDTO {

     @JacksonXmlProperty(localName = "name",isAttribute = true)
     private String name="Whatever";

}

Any advise would be much appreciated.

Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33
tpal
  • 1
  • 1
  • 1

2 Answers2

0

To do this, you may need to implement more classes like you have already done and then add related properties to your container class ItemsDTO:

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName = "item")
public class ItemsDTO {

    @JacksonXmlProperty(isAttribute = true)
    private String name = "Whatever";

    @JacksonXmlProperty(localName = "problem_id")
    private ProblemId problemId = new ProblemId();

    @JacksonXmlProperty(localName = "problem_type")
    private ProblemType problemType = new ProblemType();

    @JacksonXmlProperty(localName = "problem_desc")
    private ProblemDesc problemDesc = new ProblemDesc();
}

class ProblemId {
    @JacksonXmlProperty(isAttribute = true)
    private int id = 12312;
}

class ProblemType {
    @JacksonXmlProperty(isAttribute = true)
    private int type = 1765;
}

class ProblemDesc {
    @JacksonXmlProperty(isAttribute = true)
    private String desc = "faulty";
}

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

Although it would be better to have a shorter XML output with problem's properties "encapsulated" in a single element like this:

<item name="Whatever">
  <problem id="12312" type="1765" desc="faulty"/>
</item>

This can be achieved with the following code:

@JacksonXmlRootElement(localName = "item")
public class ItemDTO {

    @JacksonXmlProperty(isAttribute = true)
    private String name = "Whatever";

    @JacksonXmlProperty
    private Problem problem = new Problem();
}

class Problem {
    @JacksonXmlProperty(isAttribute = true)
    private int id = 12312;

    @JacksonXmlProperty(isAttribute = true)
    private int type = 1765;

    @JacksonXmlProperty(isAttribute = true)
    private String desc = "faulty";
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42