How to handle Json body in post request in jax-rs
I have a project (homework) about JAX-RS. I work with NetBeans, Jersey and Tomcat.
This is my User class for the main object on the system.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="user")
public class User {
//@XmlElement
//public int id ;
@XmlElement
public String username;
@XmlElement
public String fullname;
@XmlElement
public String gender;
@XmlElement
public String birthDate;
public User(){
}
public User(String username,String fullname, String gender,String birthDate){
//this.id = id;
this.username = username;
this.fullname = fullname;
this.gender = gender;
this.birthDate = birthDate;
}
}
This is my "JAXBContextResolver" class
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext>{
private JAXBContext context;
private Class[] types = {User.class};
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext( JSONConfiguration.mapped().build(), types);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
for (Class type : types) {
if (type == objectType) {
return context;
}
}
return null;
}
}
And this is my post method in the "UserService" class
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<User> createNewUser(User tUser) {
List<User> list = new ArrayList<User>();
list.add(tUser);
return list;
}
When I try to post a new user to localhost using RESTClient (Firefox add-on), my request body is a json input like this:
{"user":{"username":"blabla","fullname":"blabla","gender":"M","birthDate":"05.01.1978"}}
In the post method (in the UserService class) is the "tUser" variable automatically populated with incoming input? The "tUser" variable shows zero elements in it in debug mode:
If I am wrong, can someone correct me please? Why do these values show zero? Shouldn't they show "blabla" - "blabla" - "M" - "01/05/1878"? could you help me?
source to share
I solved this problem; In the JAXBContextResolver class, I change the method as follows:
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext( JSONConfiguration.mapped().rootUnwrapping(false).build(), types);
}
The difference from the first is the addition of the expression rootUnwrapping (false).
source to share
@XmlRootElement
doesn't work in your example. Send message
{"username":"blabla","fullname":"blabla","gender":"M","birthDate":"05.01.1978"}
instead of
EDIT
1)
public List<User> createNewUser(Request tUser)
and class
class Request
{
public User user;
}
2)
public List<User> createNewUser(String tUser)
and convert String
to object using google-gson
orjackson json processor
source to share