为什么json字符串以不同的格式到达一个宁静的服务?

时间:2013-09-11 06:30:24

标签: java jquery rest

我想使用post方法将json字符串发送到restful服务。它正在发送,但服务器端收到的数据格式不同。我错过了什么?

这是我在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;
}

}

我使用jquery调用上述服务,如下所示。

   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);
     }
 });

我发送此声明

var user="{'serviceInfo': [{'name':'All'}]}"; 

在宁静的服务中,我将其视为

user=%7B'serviceInfo'%3A+%5B%7B'name'%3A'All'%7D%5D%7D

我不知道为什么添加了%和其他数字。

3 个答案:

答案 0 :(得分:1)

  

我不知道为什么添加了%和其他数字。

%和数字是URL编码。某些字符(实际上是字节)正在被%xx替换,其中xx是一对表示字节的十六进制数字。

问题是您的客户端传递的Javascript对象具有JSON字符串属性。你应该对它进行字符串化,如@ishwar所述。

jquery.ajax documentation说:

  

要发送到服务器的数据。如果不是字符串,它将转换为查询字符串。 ...

所以发生的事情是您的对象正在转换为URL查询字符串...完成URL编码。

答案 1 :(得分:0)

试  数据:JSON.stringify(用户),  它会起作用。

答案 2 :(得分:0)

首先,您的user变量不合法JSON - 它使用了错误的字符串终止符(JSON需要围绕键和字符串使用双引号,而不是单引号)。

其次,它会自动转换为x-www-form-urlencoded编码,并带有%xx替换,因为你没有告诉过jQuery。

尝试以下操作,在AJAX POST请求的正文中张贴“普通JS对象”:

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
    ...
});
相关问题