I’m having following method in my resource class for a REST service in Java.
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Player createCustomer(Customer customer)
{
System.out.println("Request for Create");
System.out.println(""+customer.getID()+"\n"+customer.getTableID()+"\n"+customer.getCustNick());
//Above statement should print the details I send via JSON object
//return custdao.create(customer); //Want to call this to add new "customer" into database table.
return player;
}
And following the jQuery method I call when input fields in the form are filled and create button is clicked.
function createEntry() {
var formData = JSON.stringify({
"ID" : $("input[name='txtID']").val(),
"tableID" : $("input[name='txtTableID']").val(),
"custNick" : $("input[name='txtNick']").val()
});
console.log(formData); //Just to see if form details are JSON encoded.
$.ajax({
type: "POST",
contentType: "application/json",
url: baseURL,
dataType: "json",
data: formData,
success: function(data) {
console.log("Customer Added!");
$("div.response").append("<h3>New Customer ("+ $("input[name='txtNick']").val() +") Added on the Server</h3>");
}
});
}
But on server, I’m getting empty “customer” object, what am I doing wrong here? Please let me know if you need any further details (regarding Customer class model).
Update: Following is Customer class.
/*ignore imports, all required imports are included */
@XmlRootElement
public class Customer
{
private int id;
private int tableid;
private String custnick;
public int getID()
{
return id;
}
public void setID(int id)
{
this.id = id;
}
....
....
/* Similar Setter-Getter Methods for the fields */
}
I guess the problem has something to do with XML schema of my “Customer” class and the node names I send in JSON object is not matching with schema that’s why it may not be able to map fields with setter methods of my model class, not sure though.
The problem is probably caused by a field name mismatch.
You can use the
@XmlElementJAXB annotation on your entity class to set whatever names you want for your fields to make it all clear. Just follow this link: http://jaxb.java.net/tutorial/section_6_2_7_1-Annotations-for-Fields.html#Annotations%20for%20Fields