如何在XML中传递@RequestBody对象列表

时间:2019-03-26 09:50:48

标签: java xml spring spring-boot jaxb

我有一个带有PostMapping的rest应用程序:

public List<Job> jobs = new ArrayList<Job>()
@PostMapping
public JobList handleXMLPostRequest (@Valid @RequestBody JobList newJobs)
    {
        for(Job joba : newJobs.getJobList())
        jobs.add(joba);

        for (Job joba : jobs)
            System.out.println(joba.toString());

    System.out.println("\n");
    return newJobs;
    }

对象作业:

@XmlRootElement(name = "job")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Job {
    private int id;
    private String type;
    private String user;
    private String device;
    private int amount;
    //getters and setters }

对象jobList:

@XmlRootElement(name = "jobs")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class JobList {
    public ArrayList<Job> jobList = new ArrayList<>();
    //getter setter
}

尝试发布下一个XML:

<jobs>
    <job>
        <id>10</id>
        <type>print</type>
        <user>user1</user>
        <device>device1</device>
        <amount>10</amount>
    </job>
    <job>
        <id>11</id>
        <type>scan</type>
        <user>user1</user>
        <device>device1</device>
        <amount>10</amount>
    </job>
</jobs>

我需要将读为JobList,其中每个将是此列表中的Job对象。

当我运行示例并将此xml列表传递给它时,它返回空列表。 如何正确设置此JobList?

1 个答案:

答案 0 :(得分:0)

尝试一下,

JobsList.java

@XmlRootElement(name = "jobs")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class JobList {

    private ArrayList<Job> jobList;

    @XmlElement(name="job")
    public ArrayList<job> getJobList(){
        return jobList;
    }

    public void setJobList(ArrayList<Job> jobList){
        this.jobList = jobList;
    }
}

Job.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Job {

    private int id;
    private String type;
    private String user;
    private String device;
    private int amount;

    @XmlElement
    public int getId(){
        return id;
    }

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

    @XmlElement
    public String getType(){
        return type;
    }

    public void setType(String type){
        this.type = type;
    }

    @XmlElement
    public String getUser(){
        return user;
    }

    public void setUser(String iser){
        this.user = user;
    }

    @XmlElement
    public String getDevice(){
        return device;
    }

    public void setDevice(String device){
        this.device = device;
    }

    @XmlElement
    public int getAmount(){
        return amount;
    }

    public void setAmount(int amount){
        this.amount = amount;
    }

}