本文介绍了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 路径匹配但参数(或 headers 之类的)不匹配时,您通常会看到此类错误处理程序方法期望什么.

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 请求的整个主体映射到一个对象.我猜你的 body 不仅仅是一个字符串,而是一些完整的 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 声明中的参数,例如

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 来使其工作> 看看这是否能让您更接近可行的解决方案.

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 请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:31