MismatchedInputException: Cannot deserialize instance

This commit is contained in:
michaelin007 2023-12-01 09:14:50 +00:00
parent dea22a6863
commit 720789d026
3 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package com.baeldung.mismatchedinputexception;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Animals {
private final int id;
private String name;
public Animals(@JsonProperty("id") int id, @JsonProperty("name")String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.mismatchedinputexception;
public class Book {
private int id;
private String title;
public Book(int id, String title) {
this.id = id;
this.title = title;
}
public Book() {
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.mismatchedinputexception;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MismatchedinputExceptionUnitTest {
@Test
void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":10,\"name\":\"Dog\"}";
ObjectMapper mapper = new ObjectMapper();
Animals animal = mapper.readValue(jsonString, Animals.class);
assertEquals(animal.getId(),10);
}
@Test
void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}";
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(jsonString, Book.class);
assertEquals(book.getId(),10);
}
@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Book> book = mapper.readValue(jsonString, new TypeReference<List<Book>>(){});
assertEquals(book.get(0).getTitle(),"Harry Potter");
}
}