Facing JSON parse issue, Cannot deserialize value of type `java.lang.String` from Array value jackson.databind.exc.MismatchedInputException

Viewed 3626

Facing a JSON parse issue when trying to include array in my postman request:

{
    "id" : "0",
    "number":["2222", "3333"]
}

pojo:

public class User {
    @Getter @Setter private String      id;
    @Getter @Setter  private String[]   number;

    //i've also tried these:
    @Getter @Setter  private List<String>   number;
    @Getter @Setter  private ArrayList<String>  number;
}

Controller:

@PostMapping("/user")
    public ResponseEntity<Object> getUser(@RequestBody(required=true)User user) {

Trace:

  "trace": "org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Cannot deserialize value of type `java.lang.String` from Array value (token `JsonToken.START_ARRAY`); 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize value of type `java.lang.String` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 13] 
2 Answers

I had the same issue. Turns out, as I was sending messages from a test JS script, Stomp.js didn't automatically serialize the object passed as the message body to JSON, what it did instead was just cast it to a string and send "[Object object]" as payload, which Jackson interpreted as an array because of the [ in front, and immediately failed because it didn't expect to receive an array.

client.publish({
  destination: '/app/publish',
  body: {
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  }
}); // => "[Object object]"

Explicitly serializing the object manually before passing it as payload did the thing:

client.publish({
  destination: '/app/publish',
  body: JSON.stringify({
    id: 0,
    content: 'I am very frustrated',
    sender: 'test_user',
    chat: 0
  })
}); // => {id: 0, ...}

The issue was Javascript all along.

Add a no-argument constructor to your class and make it Serializable

Related