我有弹簧控制器:
@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = "application/json") public @ResponseBody ResponseDto<Job> add(User user) { ... }
我可以使用APACHE HTTP CLIENT张贴这样的对象:
HttpPost post = new HttpPost(url); List nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair("name", "xxx")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post);
在控制器中,我得到名称为“ xxx”的用户
现在,我想创建User对象并将其发布到服务器,我试图与GSON对象一起使用,如下所示:
User user = new User(); user.setName("yyy"); Gson gson = new Gson(); String json = gson.toJson(user); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json.toString(), HTTP.UTF_8); entity.setContentType("application/json"); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost);
但是以这种方式,我进入具有空字段的服务器用户对象…
我该如何解决?
好了,您缺少一些东西:
User
HttpMessageConverter
@RequestBody
@JsonIgnoreProperties(ignoreUnknown = true)