Merge pull request #15339 from Michaelin007/jackson
MismatchedInputException: Cannot deserialize instance
This commit is contained in:
commit
7213e42992
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue