Skip to content

Commit 089162e

Browse files
BAEL-2412
Add new code examples when deserializing real numbers to discrete number types.
1 parent 24bd464 commit 089162e

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.baeldung.gson.primitives.models;
2+
3+
public class LongExample {
4+
public long value = 1;
5+
6+
public String toString() {
7+
return "{byte: " + value + "}";
8+
}
9+
}

‎gson/src/test/java/org/baeldung/gson/primitives/UnitTest.java‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public class UnitTest {
7575
assertEquals(44, model.value);
7676
}
7777

78-
@Test public void fromJsonNonCompatibleNumberTypes() {
78+
@Test public void fromJsonRealToByte() {
7979
Gson gson = new Gson();
8080
String json = "{\"value\": 2.3}";
8181
try {
@@ -89,6 +89,27 @@ public class UnitTest {
8989
fail();
9090
}
9191

92+
@Test public void fromJsonRealToLong() {
93+
Gson gson = new Gson();
94+
String json = "{\"value\": 2.3}";
95+
try {
96+
gson.fromJson(json, LongExample.class);
97+
} catch (Exception ex) {
98+
assertTrue(ex instanceof JsonSyntaxException);
99+
assertTrue(ex.getCause() instanceof NumberFormatException);
100+
return;
101+
}
102+
103+
fail();
104+
}
105+
106+
@Test public void fromJsonRealToLongEndingIn0() {
107+
Gson gson = new Gson();
108+
String json = "{\"value\": 2.0}";
109+
LongExample model = gson.fromJson(json, LongExample.class);
110+
assertEquals(2, model.value);
111+
}
112+
92113
@Test public void fromJsonUnicodeChar() {
93114
Gson gson = new Gson();
94115
String json = "{\"value\": \"\\u00AE\"}";

0 commit comments

Comments
 (0)