在REST URL中传递JSON字符串


问题内容

第一次使用REST并尝试将JSON字符串作为REST请求URL中的路径变量发送,我正在做的是从客户端发送请求:

JSONObject json = new JSONObject();
try {
    json.put("Test", "123");
    json.put("tracks", "1234");
    jj = json.toString();
} catch (JSONException e1) {
    // TODO Auto-generated catch block
       e1.printStackTrace();
}

   String url =  "http://localhost:8090/webApp/restresource/"+jj+".do";
   st = (String) restTemplate.postForObject(url,jj, String.class, jj);

休息服务器:

@RequestMapping(value = "/restresource/{code}", method=RequestMethod.POST, consumes= "application/json")
public @ResponseBody String useJson(@PathVariable String jj) {

    String result;

    JSONObject jObject = new JSONObject();
    try {
        result = jObject.getJSONObject(jj).toString();

    } catch (JSONException jse) {
        jse.printStackTrace();
    }

return result;

}

我得到的例外是 not enough variable values to expand "Test"

编辑:我的请求网址看起来像这样:

http://localhost:8090/app/restResource/%7B%22%22:%22123%22,%22tracks%22:%221234%22%7D.do

甚至看到了HttpClientErrorException!任何帮助表示赞赏!


问题答案:

我会做的是:

HttpEntity<Object> entity = new HttpEntity<Object>(json); // Create HTTP Entity to post to rest endpoint
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.postForEntity(url, entity, Object.class);

在服务器端,您不需要以PathVariable的身份访问它,而是可以使用

@RequestMapping(value = "/restresource", method=RequestMethod.POST, consumes= "application/json")
public @ResponseBody String useJson(@RequestBody JSonObject object) {

因此,spring框架会自动将json字符串转换为指定的对象类型。您可以相应地调整网址,然后重试。