Spring MVC:不反序列化JSON请求体 [英] Spring MVC: Doesn't deserialize JSON request body

查看:115
本文介绍了Spring MVC:不反序列化JSON请求体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Spring MVC项目,我需要完成的任务之一要求我在POST请求中通过用户发送一串JSON数据。我知道Spring会使用Jackson将JSON反序列化为对象,但如果我尝试以下内容:

I'm working on a Spring MVC project and one of the tasks I need to do requires me to have a string of JSON data sent through by the user in a POST request. I know that Spring will deserialize JSON using Jackson to objects, but if I try something like the following:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public void doSomething(@RequestBody String json) {
    // do something
}

我只是回复了HTTP 400错误请求(客户端发送的请求在语法上不正确。)。

I simply get HTTP 400 Bad Request back ("The request sent by the client was syntactically incorrect.").

如何将客户端发送的原始JSON作为字符串?

How can I get the raw JSON sent by the client as a string?

推荐答案

您通常会看到这个Spring MVC找到与URL路径匹配的请求映射但参数(或标题或某些内容)与处理程序方法所期望的不匹配时的错误类型。

You will usually see this type of error when Spring MVC finds a request mapping that matches the URL path but the parameters (or headers or something) don't match what the handler method is expecting.

如果您使用@RequestBody注释,那么我相信Spring MVC期望将POST请求的整个主体映射到Object。我猜你的身体不仅仅是一个字符串,而是一些完整的JSON对象。

If you use the @RequestBody annotation then I believe Spring MVC is expecting to map the entire body of the POST request to an Object. I'm guessing your body is not simply a String, but some full JSON object.

如果你有一个你期望的JSON对象的java模型,那么你可以替换doSomething声明中的String参数,例如

If you have a java model of the JSON object you are expecting then you could replace the String parameter with that in your doSomething declaration, such as

public void doSomething(@RequestBody MyObject myobj){

如果您没有与JSON匹配的Java对象,那么您可以尝试通过替换 String 键入 Map< String,Object> ,看看是否能让您更接近工作解决方案。

If you don't have a Java object that matches the JSON then you could try to get it working by replacing the String type with a Map<String, Object> and see if that gets you closer to a working solution.

你也可以打开Spring MVC中的调试日志记录,以获得更多关于它是一个错误请求的信息。

You could also turn on debug logging in Spring MVC to get more information on why it was a bad request.

编辑:
在评论中给出您的要求,您只需将HttpServletRequest注入您的方法并自己阅读正文。

Given your requirements in the comments, you could simply inject the HttpServletRequest into your method and read the body yourself.

public void doSomething(HttpServletRequest request) {
  String jsonBody = IOUtils.toString( request.getInputStream());
  // do stuff
}

这篇关于Spring MVC:不反序列化JSON请求体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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