Rest方法:返回XML的集合而不是正确的分组

时间:2018-05-08 18:27:01

标签: java rest

我有以下POJO:

@XmlRootElement(name = "User")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;
    private String name;
    private String profession;

    public User() {
    }

    public User(int id, String name, String profession) {
        this.id = id;
        this.name = name;
        this.profession = profession;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

该服务定义为:

@GET 
@Path("/users") 
@Produces(MediaType.APPLICATION_XML) 
List<User> getUsers();

当我使用REST客户端(Java或Postman)拨打电话时,我得到以下XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<collection>
    <User>
        <id>1</id>
        <name>Mahesh</name>
        <profession>Teacher</profession>
    </User>
</collection>

为什么返回的XML包含<collection>而不是<Users>

1 个答案:

答案 0 :(得分:2)

List<User>换行到单独的对象中,并对该集合使用@XMLElementWrapper

https://docs.oracle.com/javase/7/docs/api/javax/xml/bind/annotation/XmlElementWrapper.html

我没有测试过,但您可以尝试在@XMLElementWrapper上使用getUsers()