Spring Boot JSON parse error: Cannot construct instance of model

Viewed 5325

I am catching error:

Resolved [org.springframework.http.converter.
HttpMessageNotReadableException: JSON parse error: Cannot 
construct instance of `model.Record` (although at least one Creator exists): no 
int/Int-argument constructor/factory method to deserialize from Number value (2); 
nested exception is com.fasterxml.jackson.databind.exc.
MismatchedInputException: Cannot construct instance of 
`model.Record` (although at least
 one Creator exists): no int/Int-argumentconstructor/factory
 method to deserialize from Number value (2)
 at [Source: (PushbackInputStream); line: 1, column: 123] (through reference chain: 
model.CreateUserRequestDTO["records"]->java.util.ArrayList[0])]

I have 2 entities: User and Record.

public class Developer{
    private long id;
    private String name;
    private List<Record> records;
}

Second class:

@Data
public class Record{
    private long id;
    private String title;
}

In my front end I have a records select with multiple options, where value is id and title - I'm displaying as options.

When I try to send my request to server, request looks like:

{
  "name": "Ivan",
  "records": [1, 3, 7] // selected options
}

How can I fix it? Shouldn't Spring Boot take id and make entities from them?

2 Answers

Your JSon is not correct, it doesn't match with your class, it should look like this:

{
  "name": "Ivan",
  "records": [
    {
      "id": 1
    },
    {
      "id": 2
    },
    {
      "id": 3
    }
  ]
}

Every Record in List<Record> is other object, so when you using JSON array, inside have to be object in { }. Instead of:

{
    "records": [ 1 ]
}

You have to use:

{
    "records": [
        {
            "id": 1
        }
    ]
}

Think about how you would put an additional title field in your JSON syntax. In correct syntax, you just only shoud add new field:

{
    "records": [
        {
            "id": 1,
            "title": "foo"
        }
    ]
}
Related