|
1 | 1 | package org.baeldung.jackson.test; |
2 | 2 |
|
3 | 3 | import static org.hamcrest.Matchers.equalTo; |
| 4 | +import static org.hamcrest.Matchers.notNullValue; |
4 | 5 | import static org.junit.Assert.assertNotNull; |
5 | 6 | import static org.junit.Assert.assertThat; |
6 | 7 |
|
7 | 8 | import java.io.IOException; |
8 | 9 |
|
| 10 | +import org.baeldung.jackson.deserialization.ItemDeserializer; |
| 11 | +import org.baeldung.jackson.dtos.Item; |
| 12 | +import org.baeldung.jackson.dtos.ItemWithSerializer; |
9 | 13 | import org.baeldung.jackson.dtos.MyDto; |
10 | 14 | import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown; |
11 | 15 | import org.junit.Test; |
|
18 | 22 | import com.fasterxml.jackson.databind.JsonNode; |
19 | 23 | import com.fasterxml.jackson.databind.ObjectMapper; |
20 | 24 | import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; |
21 | | - |
| 25 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
22 | 26 |
|
23 | 27 | public class JacksonDeserializationUnitTest { |
24 | 28 |
|
@@ -130,4 +134,35 @@ public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws |
130 | 134 | assertThat(jsonNode1.textValue(), equalTo("v1")); |
131 | 135 | } |
132 | 136 |
|
| 137 | + // custom deserialization |
| 138 | + |
| 139 | + @Test |
| 140 | + public final void whenDeserializingTheStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { |
| 141 | + final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":{\"id\":2,\"name\":\"theUser\"}}"; |
| 142 | + |
| 143 | + final Item readValue = new ObjectMapper().readValue(json, Item.class); |
| 144 | + assertThat(readValue, notNullValue()); |
| 145 | + } |
| 146 | + |
| 147 | + @Test |
| 148 | + public final void whenDeserializingANonStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { |
| 149 | + final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":2}"; |
| 150 | + final ObjectMapper mapper = new ObjectMapper(); |
| 151 | + |
| 152 | + final SimpleModule module = new SimpleModule(); |
| 153 | + module.addDeserializer(Item.class, new ItemDeserializer()); |
| 154 | + mapper.registerModule(module); |
| 155 | + |
| 156 | + final Item readValue = mapper.readValue(json, Item.class); |
| 157 | + assertThat(readValue, notNullValue()); |
| 158 | + } |
| 159 | + |
| 160 | + @Test |
| 161 | + public final void givenDeserializerIsOnClass_whenDeserializingCustomRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { |
| 162 | + final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":2}"; |
| 163 | + |
| 164 | + final ItemWithSerializer readValue = new ObjectMapper().readValue(json, ItemWithSerializer.class); |
| 165 | + assertThat(readValue, notNullValue()); |
| 166 | + } |
| 167 | + |
133 | 168 | } |
0 commit comments