This seems like another fairly simple thing to do, but I’m again struggling on how to do it.
I have a POJO, with Jersey/JAXB annotations that has HTTP POST and GET methods associated to it. When doing POST on the POJO, the request body is sent as a JSON, essentially modeling the POJO. When doing GET, I want to return the POJO, but with only a subset of the POJO properties.
I tried using @XmlTransient on the properties I don’t want for the GET, but then I cannot use those properties during the HTTP POST.
First, here is my POJO (User.java)
import javax.xml.bind.annotation.*
@XmlRootElement
public class User {
private String userName;
private String userEmail;
private String userType; // Do not return this property in GET
private String userTmpPassword; // Do not return this property in GET
// User constructor
public User(String userName,...) {
this.userName = userName;
//...etc...
}
// getters and setters with @XmlElement on each attribute
//...etc...
@XmlElement(name="user_name")
public String getUserName() {
return userName;
}
public String setUserName() {
return userName;
}
//...etc...
}
Here is my RESTful service class:
public class userService{
@POST
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getUser(User userInfoAsJSON) {
User user = new User(userInfoAsJSON.getUserName(), ...);
// pseudo-code for persisting User
writeUserToDB(user);
return Response.status(200);
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getUser(String Id) {
// Pseudo-code for retrieving user
User user = retrieveUserFromDB(user);
Response.status(200).entity(user);
}
}
As expected, my JSON response for the HTTP GET returns all the properties of User, like this:
{
"user_name": "John Doe",
"user_email": "john_doe@johndoe.com",
"user_type": "Admin",
"user_tmp_password": "abc_xyz"
}
Whereas, I would like to only return a couple attributes in the JSON response:
{
"user_name": "John Doe",
"user_email": "john_doe@johndoe.com"
}
You could always return a partially populated
Userobject as by default null values are not marshalled. You may even be able to implement this in yourretrieveUserFromDBmethod to avoid the copy step.For More Information