gpt4 book ai didi

java - 在Spring中读取Content-Type application/json

转载 作者:太空宇宙 更新时间:2023-11-04 13:45:59 25 4
gpt4 key购买 nike

trying-to-use-spring-boot-rest-to-read-json-string-from-post 所示我想从 Spring RestController 中的 POST 请求读取 json 有效负载。使用内容类型“text/plain”没有问题,但使用“application/json”反序列化失败,并且出现 MessageNotReadable 异常。但实际上内容再简单不过了,只是一个空的json对象“{}”。是否缺少所需的转换器?我使用 Spring Root 版本 1.2.3.RELEASE。

编码示例

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json")
@ResponseBody
public Definitions createOrUpdateDefinitions(HttpEntity<String> httpEntity) throws IOException { ... }

curl 调用

curl -H  "Content-type: application/json" -X POST -d '{}' http://localhost:8080/deepdefinitions

错误

{"timestamp":1434397457853,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: org.apache.catalina.connector.CoyoteInputStream@122f9ce3; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: org.apache.catalina.connector.CoyoteInputStream@122f9ce3; line: 1, column: 1]","path":"/deepdefinitions"}

最佳答案

来自Spring REST guide :

The Accept and Content-Type HTTP headers can be used to describe the content being sent or requested within an HTTP request. The client may set Accept to application/json if it is requesting a response in JSON. Conversely, when sending data, setting the Content-Type to application/xml tells the client that the data being sent in the request is XML.

看来您的 Controller 只处理 Accept header :

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json")

您需要将其更改为:

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json, Content-type=application/json")

还有消费生产 elements@RequestMapping 注释中可用。

Spring MVC documentation推荐:

Although you can match to Content-Type and Accept header values using media type wild cards (for example "content-type=text/*" will match to "text/plain" and "text/html"), it is recommended to use the consumes and produces conditions respectively instead. They are intended specifically for that purpose.

<小时/>

根据您的相关帖子,您应该将方法签名更改为:

@ResponseBody
public Definitions createOrUpdateDefinitions(@RequestBody String value, HttpEntity<String> httpEntity) throws IOException

我认为你还应该更改你的curl命令,如下所示。这是因为 {}(JavaScript 对象文字)会映射到对象,而要映射到字符串,您应该使用空字符串 '' 文字。

curl -H "Content-type: application/json" -X POST -d '' http://localhost:8080/deepdefinitions

关于java - 在Spring中读取Content-Type application/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com