GAME Jersey RESTful Service POST JSON

I am trying to write a service that will accept a JSON or XML object in a POST request. I have successfully written a GET request handler that will return my object as XML or JSON as requested in the accept header. When I send POST to a service with JSON as the request body, the Java object in my POST method is not populated with values ​​from json.

@POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void postUser(@Context HttpServletRequest Req, User user) { PersistenceManager pm = PMF.get().getPersistenceManager(); try { pm.makePersistent(user); } finally { pm.close(); } } 

When I violate the POST method, the Java object "user" of type User has null values ​​for the properties. An object is not null, just properties.

This is JSON sent by POST

 {"user":{"logon":"kevin","password":"password","personid":"xyz"}} 

And here is my class

 package com.afalon.cloud.contracts; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessorType; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable @XmlRootElement(name = "user") @XmlAccessorType(XmlAccessType.NONE) public class User { @Persistent @XmlElement(name="logon") private String logon; @Persistent @XmlElement(name="password") private String password; @Persistent @XmlElement(name="personid") private String personid; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true") @XmlElement(name="userid") private String userid; public User () {} public void setLogOn(String value) { logon = value; } public String getLogOn() { return logon; } public void setPassword(String value) { password = value; } public String getPassword() { return password; } public void setPersonId(String value) { personid = value; } public String getPersonId() { return personid; } public String getUserId() { return userid; } 
+4
source share
1 answer

Perhaps no one answered my question, because the problem has such an obvious solution!

I can answer my question after I noticed my mistake.

The JSON body that I sent was formatted as a list of User objects, so if I edit

 {"user":{"logon":"kevin","password":"password","personid":"xyz"}} 

to

 {"logon":"kevin","password":"password","personid":"xyz"} 

everything works because my @POST handler does not expect a list of User objects. Alternatively, I could adapt the @POST handler to accept the List<User> parameter!

+5
source

All Articles