使用自定义包装器

时间:2017-09-18 00:08:33

标签: java xml jaxb marshalling

考虑以下POJO:

public class User {
    private String name;
    /* + getter/setter */
}

以下REST WebService:

@Path("Department")
public class DeptoREST {
    @GET @Path("{id}")
    public List<User> getEmployeesList( Integer id ) {
        return dao.fetchEmployeesFromDepto( id );
    }
}

这是结果输出:

<users>
    <user><name>Usr 1</name></user>
    <user><name>Usr 2</name></user>
    <user><name>Usr 3</name></user>
</users>

如果没有包装类,是否可以将输出更改为:

<employees>
    <employee><name>Usr 1</name></employee>
    <employee><name>Usr 2</name></employee>
    <employee><name>Usr 3</name></employee>
</employees>

1 个答案:

答案 0 :(得分:0)

您可以包装列表,而不是单个User对象:

@XmlRootElement(name="employees")
public static class EmployeeList {
    @XmlElement(name = "employee")
    private List<User> users;

    public EmployeeList() {
        users = Collections.emptyList();
    }

    public EmployeeList(List<User> users) {
        this.users = users;
    }

    public List<User> getUsers() {
        return users;
    }
}

然后:

return new EmployeeList(dao.fetchEmployeesFromDepto( id ));