Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpMessageNotReadableException when Using JSON Patch in Spring Controller

Tags:

java

json

spring

I want use Patch method following Using JSON Patch in Spring by baeldung but I have error when controller recive in @RequestBody a JsonPatch Object. If I use JsonMergePatch the controller deserialize with out problem.

Thanks

The error is: [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]]

My 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"
}

Error:

{"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"}

like image 736
Santiago KM Avatar asked Mar 02 '23 14:03

Santiago KM


1 Answers

I don't know if you have already solved it but for anyone facing this problem, it's a matter of syntax. the JsonPatch must be enclosed in []. Remember that it's an array actually, so you can change multiple values at the time. In your case it should be:

    [
      {
        "op": "replace",
        "path": "/brand",
        "value": "chevy"
      }
    ]
like image 161
Nyom Avatar answered Mar 05 '23 02:03

Nyom