如何将 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:
- 确保在客户端和服务器上以相同的方式将
User
序列化和反序列化为 json. - 如果您想使用 spring 内置的 jackson 支持(最好在客户端上也使用它)或为 Gson 包含适当的
HttpMessageConverter
,请确保在类路径上有 jackson 库.您可以使用 GsonHttpMessageConverter 来自 spring-android. - 使用
@RequestBody
注释您的请求处理程序方法参数. - 如果使用 jackson,正如@ararog 所提到的,请确保您明确排除了可以使用
@JsonIgnoreProperties(ignoreUnknown = true)
- 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)