简体   繁体   中英

How to omit an XML tag on a request with JAXB and JAX-RS?

I'm learning JAX-RS and using JAXB to marshal/unmarshal XML data which works very well. My problem is to answer a request where some XML elements should be omitted. Here's an example:

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {

@XmlAttribute
private int id;

@XmlElement
private String username;

@XmlElement
private String password;

Users class is used to wrap a list of users

@XmlRootElement(name = "users")
@XmlAccessorType(XmlAccessType.FIELD)
public class Users {

@XmlElement(name = "user")
private List<User> users = null;

public Users() {
}

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

public void setUsers(final List<User> users) {
    this.users = users;
}

}

REST resource

@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public Users getAllUsers() {

    final ArrayList<User> users = new ArrayList<User>(userDB.values());
    final Users userList = new Users();
    userList.setUsers(users);

    return userList;
}

The above generates following output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user id="1">
    <username>user1</username>
    <password>passwd0rd</password>
</user>
<user id="2">
    <username>user2</username>
    <password>passwd0rd</password>
</user>
</users>

So the question is if there is a way to instruct JAXB to omit for instance the password element (just for this request) and have an output like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user id="1">
    <username>user1</username>
</user>
<user id="2">
    <username>user2</username>
</user>
</users>

Thanks for any guidance!

The annotation you are looking for is @XmlTransient . This is will not map your field and will not be shown in the output for any request.

But if you want to specify only for certain requests then I guess you will have to set it as null explicitly for such certain requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM