如何将JSON对象发布到spring控制器? [英] How to POST JSON object to spring controller?
本文介绍了如何将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);
但是通过这种方式,我进入了具有空字段的服务器User对象...
But in this way I get in server User object with null fields...
我该如何解决?
推荐答案
好,您缺少一些东西:
- 确保您要在客户端和服务器上以相同的方式将
User
序列化和反序列化为json. - 如果您想使用spring内置的jackson支持(最好也可以在客户端上使用)或确保对Gson包含适当的
HttpMessageConverter
,请确保在类路径上具有jackson库.您可以使用
- Make sure you are serializing and deserializing
User
to json the same way on the client and server. - 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. - Annotate your request handler method parameter with
@RequestBody
. - 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屋!
查看全文