Search code examples
javaspringjacksonjackson-databind

Jackson deserialization error: MismatchedInputException


I have the following class

public class Cart {
    private final String id;

    public Cart(String id) { this.id = id;}

    public String getId() { return id; }
}

And the following test:

    String jsonString = "{\"id\":\"56c7b5f7-115b-4cb9-9658-acb7b849d5d5\"}";
    Cart cart = mapper.readValue(jsonString, Cart.class);
    assertThat(cart.getId()).isEqualTo("56c7b5f7-115b-4cb9-9658-acb7b849d5d5");

And I'm getting the following error:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.store.domain.model.Cart (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (String)"{"id":"56c7b5f7-115b-4cb9-9658-acb7b849d5d5"}"; line: 1, column: 2]

I can't figure out what's wrong here. Any help please?


Solution

  • You need to define your bean as:

    public class Cart {
        private final String id;
    
        @JsonCreator
        public Cart(@JsonProperty("id") String id) { this.id = id;}
    
        public String getId() { return id; }
    }
    
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "{\"id\":\"56c7b5f7-115b-4cb9-9658-acb7b849d5d5\"}";
        Cart cart = mapper.readValue(jsonString, Cart.class);
        System.out.println(mapper.writeValueAsString(cart));
    }
    

    Output

    {"id":"56c7b5f7-115b-4cb9-9658-acb7b849d5d5"}
    

    By default Jackson creates instance of any class using default constructor and setter / getter method.
    Since your bean is immutable i.e. no default constructor and setter, you need to explicitly tell Jackson how to create instance of Cart class using @JsonCreator and how to set properties values using @JsonProperty.