Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.byteValue());
out.value((Number) value.byteValue());
}
}
};
Expand Down Expand Up @@ -249,7 +249,7 @@ public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.shortValue());
out.value((Number) value.shortValue());
}
}
};
Expand Down Expand Up @@ -277,7 +277,7 @@ public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.intValue());
out.value((Number) value.intValue());
}
}
};
Expand Down
27 changes: 27 additions & 0 deletions gson/src/test/java/com/google/gson/functional/PrimitiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,33 @@ public void testIntSerialization() {
assertThat(gson.toJson(1.5, Integer.class)).isEqualTo("1");
}

/** Regression test for https://github.com/google/gson/issues/2680 */
@Test
public void testToJsonTreePreservesIntegralType() {
// toJsonTree should preserve the Number type, not widen byte/short/int to Long
assertThat(gson.toJsonTree((byte) 1, byte.class).getAsNumber().getClass())
.isEqualTo(Byte.class);
assertThat(gson.toJsonTree((byte) 1, Byte.class).getAsNumber().getClass())
.isEqualTo(Byte.class);

assertThat(gson.toJsonTree((short) 1, short.class).getAsNumber().getClass())
.isEqualTo(Short.class);
assertThat(gson.toJsonTree((short) 1, Short.class).getAsNumber().getClass())
.isEqualTo(Short.class);

assertThat(gson.toJsonTree(1, int.class).getAsNumber().getClass()).isEqualTo(Integer.class);
assertThat(gson.toJsonTree(1, Integer.class).getAsNumber().getClass()).isEqualTo(Integer.class);

// Long should remain Long
assertThat(gson.toJsonTree(1L, long.class).getAsNumber().getClass()).isEqualTo(Long.class);
assertThat(gson.toJsonTree(1L, Long.class).getAsNumber().getClass()).isEqualTo(Long.class);

// Narrowing conversion should produce the target type
assertThat(gson.toJsonTree(1.5, Integer.class).getAsNumber().getClass())
.isEqualTo(Integer.class);
assertThat(gson.toJsonTree(1L, Byte.class).getAsNumber().getClass()).isEqualTo(Byte.class);
}

@Test
public void testLongSerialization() {
assertThat(gson.toJson(1L, long.class)).isEqualTo("1");
Expand Down
Loading