java - 在 Spring Controller 中使用 JSON Patch 时出现 HttpMessageNotReadableException

标签 java json spring

我想在 Using JSON Patch in Spring 之后使用 Patch 方法由 baeldung 编写,但是当 Controller 在 @RequestBody 中接收到 JsonPatch 对象时出现错误。
如果我使用 JsonMergePatch Controller 反序列化没有问题。

谢谢

错误是:[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList<com.github.fge.jsonpatch.JsonPatchOperation>` out of FIELD_NAME token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<com.github.fge.jsonpatch.JsonPatchOperation>` out of FIELD_NAME token at [Source: (PushbackInputStream); line: 2, column: 5]]
我的 Controller :

   public ResponseEntity<carsDTO> modifyCars(@RequestBody JsonPatch jsonMergePatch,HttpServletRequest headers)
throws JsonPatchException, JsonProcessingException {...

curl :
$ curl --location --request PATCH 'http://localhost:8080/api/v1.0/cars' --header 'Authorization: 
Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyb25hbGQiLCJpYXQiOjE1ODY3MzUyNjEsImV4cCI6MTU4NjczODg2MX0.FHcxAhOze
8T-OExc40PlSduAf53T-nLUY5-3E8X4heaSScvcRNGw3LTK07xzC65ZUKYeBeyTwf1Ffq9d-IRkkA' --header 
'Content-Type: application/json-patch+json' --data-raw '{
    "op": "replace",
    "path": "/brand",
    "value": "chevy"
}

错误:
{"timestamp":"2020-04-13T00:23:23.143+0000","status":400,"error":"Bad Request","message":"JSON parse error: 
Cannot deserialize instance of `java.util.ArrayList<com.github.fge.jsonpatch.JsonPatchOperation>` 
out of FIELD_NAME token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize instance of `java.util.ArrayList<com.github.fge.jsonpatch.JsonPatchOperation>` 
out of FIELD_NAME token\n at [Source: (PushbackInputStream); line: 2, column: 5]","path":"/api/v1.0/cars"}

最佳答案

我不知道你是否已经解决了它,但对于任何面临这个问题的人来说,这是一个语法问题。 JsonPatch 必须包含在 [] 中。请记住,它实际上是一个数组,因此您可以一次更改多个值。
在你的情况下,它应该是:

    [
      {
        "op": "replace",
        "path": "/brand",
        "value": "chevy"
      }
    ]

关于java - 在 Spring Controller 中使用 JSON Patch 时出现 HttpMessageNotReadableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61180067/

相关文章:

javascript - Javascript 中有没有办法只从 JSON 对象获取值?

java - 在线 Java 的 JSON 解析器

javascript - 从非表单部分检索 Servlet 信息

java - Spring 3.0如何实现脚手架

java - 我可以使用代码来控制 Spring Boot 中 ApplicationContext 做出的依赖解析决策吗?

java - 如何使用 Angular 4 在 Spring Boot 中显示存储的图像?

java - 如何使 boolean 值持续一段时间?

java - 如何将 `java.nio.file.Path` 中的反斜杠 (\) 替换为正斜杠 (/)?

java - 在 Swing 中使用线程的困难

java - 如何在 Spring Batch 中抛出自定义异常?