小编典典

如何将JSON对象发布到spring控制器?

spring-mvc

我有弹簧控制器:

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

但是以这种方式,我进入具有空字段的服务器用户对象…

我该如何解决?


阅读 230

收藏
2020-06-01

共1个答案

小编典典

好了,您缺少一些东西:

  1. 确保User在客户端和服务器上以相同的方式对json 进行序列化和反序列化。
  2. 如果要使用spring内置的jackson支持(最好在客户端上最好也使用它)或HttpMessageConverter为Gson 包含适当的属性,请确保在类路径上具有jackson库。您可以为此使用spring-android中的GsonHttpMessageConverter
  3. 用注释您的请求处理程序方法参数@RequestBody
  4. 在使用杰克逊的情况下,如@ararog所述,请确保您专门排除可被填充或用以下注释整个User类的字段@JsonIgnoreProperties(ignoreUnknown = true)
2020-06-01