如何将 JSON 对象发布到 spring 控制器? [英] How to POST JSON object to spring controller?

查看:31
本文介绍了如何将 JSON 对象发布到 spring 控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有弹簧控制器:

@RequestMapping(value = "/add", method = RequestMethod.POST, 
     consumes = "application/json")
public @ResponseBody ResponseDto<Job> add(User user) {
    ...
}

我可以像这样使用 APACHE HTTP CLIENT 发布对象:

I can POST the object like this with 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"的用户

In controller I get user with name "xxx"

现在我想创建 User 对象并将其发布到服务器,我试图像这样使用 GSON 对象:

Now I want to create User object and post it to the server, I tried to use with GSON object like this :

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

但是通过这种方式,我进入了带有空字段的服务器用户对象...

But in this way I get in server User object with null fields...

我该如何解决?

推荐答案

好吧,你还缺少一些东西:

Ok a few things you're missing:

  1. 确保在客户端和服务器上以相同的方式将 User 序列化和反序列化为 json.
  2. 如果您想使用 spring 内置的 jackson 支持(最好在客户端上也使用它)或为 Gson 包含适当的 HttpMessageConverter,请确保在类路径上有 jackson 库.您可以使用 GsonHttpMessageConverter 来自 spring-android.
  3. 使用 @RequestBody 注释您的请求处理程序方法参数.
  4. 如果使用 jackson,正如@ararog 所提到的,请确保您明确排除了可以使用 @JsonIgnoreProperties(ignoreUnknown = true)
  1. Make sure you are serializing and deserializing User to json the same way on the client and server.
  2. Make sure to have jackson libraries on the classpath if you want to use spring built-in jackson support (and preferably use that on the client as well) or include apropriate HttpMessageConverter for Gson. You can use GsonHttpMessageConverter from spring-android for that.
  3. Annotate your request handler method parameter with @RequestBody.
  4. In case of using jackson, as @ararog mentioned, make sure that you specifically exclude fields that can be ingored or annotate the whole User class with @JsonIgnoreProperties(ignoreUnknown = true)

这篇关于如何将 JSON 对象发布到 spring 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆