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
}

我只需返回HTTP400Bad Request("客户端发送的请求在语法上不正确").

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

推荐答案

当Spring MVC发现一个与URL路径匹配的请求映射,但参数(或标题或其他内容)与处理程序方法所期望的不匹配时,您通常会看到这种类型的错误.

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声明中的字符串参数替换它,比如

public void doSomething(@RequestBody MyObject myobj) {

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中打开调试日志(log)记录,以获得关于为什么这是一个错误请求的更多信息.

Edit:

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

Json相关问答推荐

您可以使用Jolt对JSON执行OR条件吗

如何将加权边列表导出到JSON树?

如何在改装Android中将ResponseBody转换为JSONObject

Oracle plsql:如何将json文件加载到嵌套表中

使用自定义类型在Golang中解析JSON数组

将JSON数组组织到菜单中

bash用jq获取第二条JSON记录

为什么 Django Rest API 序列化器没有正确序列化多对多字段

匹配来自不同数组的值

JOLT 转换仅过滤一个字段

如何将该 JSON 解析为 Kotlin 类?

如何比较 JSON 文档并返回与 Jackson 或 Gson 的差异?

获取json中某个键的索引

Python - 如何将 JSON 文件转换为数据框

字符串的 Gson 数组到 JsonArray

在 HTML 数据属性上添加 JSON 是不是很糟糕?

NSManagedObject 属性值的 NSNull 处理

如何将单引号转义成双引号转成单引号

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)

如何使用 Gson 将 JSONArray 转换为 List?