Suma1810
Suma1810

Reputation: 1

JAX-B marshalling issue

I have to do marshaling using JAX-B. I have Customer class, Person class Customer is having List<Person> personList as an attribute. I have taken

@XmlRootElement
public class Customer  {

private List<Person> personList;

@XmlElement
public List<Person> getPersonList() {
    return personList;
}

I am getting the O/P <customer><personList>person details</personList> but I want person details inside </person></dependents></customer>

Upvotes: 0

Views: 87

Answers (2)

Daniel
Daniel

Reputation: 1622

You can use @XmlElementWrapper like this one

Customer.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "customer")
public class Customer  {

    private List<Person> personList;

    @XmlElementWrapper(name = "personList")
    @XmlElement(name="person")
    public List<Person> getPersonList() {
        return personList;
    }
}

Person.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "person")
public class Person {

    private String name;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }
}

After that your output should look like the following xml

<customer>
    <personList>
        <person>
            <name>Person 1</name>
        </person>
        <person>
            <name>Person 2</name>
        </person>
    <personList>
</customer>

Upvotes: 2

Wouter Konecny
Wouter Konecny

Reputation: 3540

I am not 100% sure how your final XML should look, but this website has a great example for JAX-B which is excellent for reference (both marshalling and unmarshalling):

http://howtodoinjava.com/2013/07/30/jaxb-exmaple-marshalling-and-unmarshalling-list-or-set-of-objects/

You probably forgot to annotate the Person class.

Upvotes: 0

Related Questions