Reputation: 203
I want to send the json string to restful services using post method. It is being sent, but the data received at the server side has a different format. What have I missed?
This is my restful service in java
@Path("/CommonDemo")
public class CommonDemo
{
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String result(String user)throws ServletException, IOException
{
System.out.println(user);
return user;
}
}
I am calling the above service using the jquery as follows.
var url = "http://localhost:8080/Snefocare/CommonDemo";
var user="{'serviceInfo': [{'name':'All'}]}";
$.ajax({
type: 'POST',
url: url,
contentType: "application/json; charset=utf-8",
data:{'user':user},
success: function(data, textStatus, jqXHR) {
alert('date'+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus +' ERROR:'+ errorThrown);
}
});
I am sending it with this statement
var user="{'serviceInfo': [{'name':'All'}]}";
and in the restful service, I am seeing it as
user=%7B'serviceInfo'%3A+%5B%7B'name'%3A'All'%7D%5D%7D
I do not know why the % and other digits have been added.
Upvotes: 0
Views: 156
Reputation: 719189
I do not know why the % and other digits have been added.
The % and digits is URL encoding. Certain characters (actually, bytes) are being replaced with %xx
where xx
is a pair of hex digits representing the byte.
The problem is that your client-side is passing a Javascript object with an attribute that is a JSON string. You should be stringifying it, as described by @ishwar.
The jquery.ajax documentation says:
Data to be sent to the server. It is converted to a query string, if not already a string. ...
So what is happening is that your object is being converted to a URL query string ... complete with URL encoding.
Upvotes: 1
Reputation: 339916
Firstly, your user
variable is not legal JSON - it's using the wrong string terminator (JSON requires double quotes around keys and strings, not single quotes).
Secondly, it's being automatically converted into x-www-form-urlencoded
encoding with %xx
substitution because you haven't told jQuery not to.
Try the following to have a "plain JS object" posted in the body of an AJAX POST request:
var user= {'serviceInfo': [{'name': 'All'}]}; // JS object literal
$.ajax({
type: POST,
url: url,
contentType: "application/json; charset=utf-8"
data: JSON.stringify(user), // defer encoding to JSON until here
processData: false, // and do not URL encode the data
...
});
Upvotes: 0