开发者

Unmarshalling xml to a bean with a collection

I'm working with Redmine's xml rest api. The service returns xml like in the example below. I'm using the Jersey Client API to communicate with the restful service. Mapping the plain fields (id, name and so on) in project are no problem, but I'm having trouble with the trackers list.

<project>
    <id>2</id>
    <name>Project X</name>
    <identifier>projectx</identifier>
    <description>Description of Project X</description>
    <homepage/>
    <created_on>Sat Jul 31 18:16:59 +0200 2010</created_on>
    <updated_on>Sat Jul 31 18:16:59 +0200 2010</updated_on>

    <trackers>
        <tracker name="Bug" id="1"/>
        <tracker name="Feature" id="2"/>
        <tracker name="Support" id="3"/>
    </trackers>
</project>

Project bean, I've removed all the plain getter and setter methods.

@XmlRootElement
@XmlSeeAlso(Tracker.class)
public class Project {

    private int id;
    private String name, identifier;
    private String description;
    Date createdOn, updatedOn;

    ArrayList<Tracker> trackers = new ArrayList<Tracker>();

    public Project() {
    }

    // Removed getters and setters...

    public ArrayList开发者_StackOverflow<Tracker> getTrackers() {
        return trackers;
    }

    @XmlElement
    public void setTrackers(ArrayList<Tracker> trackers) {
        this.trackers = trackers;
    }

}

Tracker bean, again with simple getter and setters removed for readability.

@XmlRootElement
public class Tracker {

    private String name;
    private int id;

    // Removed getters

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

    @XmlAttribute
    public void setName(String name) {
        this.name = name;
    }
}

All the plain fields on project is sat as expected, but I can't get it to set the list of trackers. What am I doing wrong? The best I've managed so far is getting a list with one null value.


You need to add the following:

@XmlElementWrapper(name="trackers")
@XmlElement(name="tracker")

For more information on JAXB and collection properties see:

  • http://bdoughan.blogspot.com/2010/09/jaxb-collection-properties.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜