简体   繁体   中英

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?

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 ie 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 .

您应该添加一个普通的构造函数,而没有这样的参数:

public Cart() { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM