|
12 | 12 |
|
13 | 13 | import org.baeldung.gson.deserialization.Foo; |
14 | 14 | import org.baeldung.gson.deserialization.FooDeserializerFromJsonWithDifferentFields; |
| 15 | +import org.baeldung.gson.deserialization.FooInstanceCreator; |
| 16 | +import org.baeldung.gson.deserialization.FooWithInner; |
15 | 17 | import org.baeldung.gson.deserialization.GenericFoo; |
16 | 18 | import org.junit.Test; |
17 | 19 |
|
@@ -108,4 +110,29 @@ public void whenDeserializingJsonIntoElements_thenCorrect() { |
108 | 110 | assertEquals(targetObject.stringValue, "seven"); |
109 | 111 | } |
110 | 112 |
|
| 113 | + // new examples |
| 114 | + |
| 115 | + @Test |
| 116 | + public void whenDeserializingToNestedObjects_thenCorrect() { |
| 117 | + final String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}"; |
| 118 | + |
| 119 | + final FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class); |
| 120 | + |
| 121 | + assertEquals(targetObject.intValue, 1); |
| 122 | + assertEquals(targetObject.stringValue, "one"); |
| 123 | + assertEquals(targetObject.innerFoo.name, "inner"); |
| 124 | + } |
| 125 | + |
| 126 | + @Test |
| 127 | + public void whenDeserializingUsingInstanceCreator_thenCorrect() { |
| 128 | + final String json = "{\"intValue\":1}"; |
| 129 | + |
| 130 | + final GsonBuilder gsonBldr = new GsonBuilder(); |
| 131 | + gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator()); |
| 132 | + final Foo targetObject = gsonBldr.create().fromJson(json, Foo.class); |
| 133 | + |
| 134 | + assertEquals(targetObject.intValue, 1); |
| 135 | + assertEquals(targetObject.stringValue, "sample"); |
| 136 | + } |
| 137 | + |
111 | 138 | } |
0 commit comments