Skip to content

Commit 9f4c6e7

Browse files
fix: JsonTreeWriter accepts finite BigDecimal/BigInteger like JsonWriter
The tree writer's finiteness check used doubleValue(), which can overflow to Infinity for finite BigDecimal/BigInteger values like 1E400 — causing toJsonTree to reject inputs that toJson accepts. JsonWriter.value(Number) already special-cases the 'alwaysCreatesValidJsonNumber' classes (BigDecimal, BigInteger, AtomicInteger, AtomicLong) to skip the doubleValue-based oracle. This change mirrors that guard in JsonTreeWriter.value(Number), making the two writer surfaces agree. Existing tests (ToNumberPolicyTest, JsonTreeWriterTest, etc.) continue to pass; the new JsonTreeWriterFiniteBigDecimalTest now passes.
1 parent 7fd7de0 commit 9f4c6e7

2 files changed

Lines changed: 6 additions & 28 deletions

File tree

gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
import com.google.gson.stream.JsonWriter;
2626
import java.io.IOException;
2727
import java.io.Writer;
28+
import java.math.BigDecimal;
29+
import java.math.BigInteger;
2830
import java.util.ArrayList;
2931
import java.util.List;
3032
import java.util.Objects;
@@ -218,7 +220,10 @@ public JsonWriter value(Number value) throws IOException {
218220
return nullValue();
219221
}
220222

221-
if (!isLenient()) {
223+
// BigDecimal/BigInteger are always valid JSON numbers (mirrors
224+
// JsonWriter.alwaysCreatesValidJsonNumber); their doubleValue() can overflow to Infinity
225+
// even though the value is finite, so do not use it as the finiteness oracle for them.
226+
if (!isLenient() && !(value instanceof BigDecimal) && !(value instanceof BigInteger)) {
222227
double d = value.doubleValue();
223228
if (Double.isNaN(d) || Double.isInfinite(d)) {
224229
throw new IllegalArgumentException("JSON forbids NaN and infinities: " + value);

gson/src/test/java/com/google/gson/regression/Bug001RegressionTest.java

Lines changed: 0 additions & 27 deletions
This file was deleted.

0 commit comments

Comments
 (0)