diff --git a/gson/src/main/java/com/google/gson/internal/bind/JdkOptionalTypeAdapters.java b/gson/src/main/java/com/google/gson/internal/bind/JdkOptionalTypeAdapters.java index 915a8883b2..894f46e1fb 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/JdkOptionalTypeAdapters.java +++ b/gson/src/main/java/com/google/gson/internal/bind/JdkOptionalTypeAdapters.java @@ -62,7 +62,10 @@ public TypeAdapter create(Gson gson, TypeToken typeToken) { } else if (rawType == OptionalLong.class) { adapter = OPTIONAL_LONG; } else if (rawType == OptionalDouble.class) { - adapter = OPTIONAL_DOUBLE; + // Use the adapter for primitive double, mirroring what + // ReflectiveTypeAdapterFactory uses for a double field and what is used + // for the elements of a double[] array. + adapter = new OptionalDoubleAdapter(gson.getAdapter(double.class)).nullSafe(); } // Safe because adapter matches rawType @SuppressWarnings("unchecked") @@ -177,41 +180,53 @@ public void write(JsonWriter out, OptionalLong value) throws IOException { } }.nullSafe(); - private static final TypeAdapter OPTIONAL_DOUBLE = - new TypeAdapter() { - @Override - public OptionalDouble read(JsonReader in) throws IOException { - boolean isPresent = false; - double value = 0; - in.beginObject(); - while (in.hasNext()) { - String name = in.nextName(); - switch (name) { - case "isPresent": - isPresent = in.nextBoolean(); - break; - case "value": - value = in.nextDouble(); - break; - default: - in.skipValue(); + private static final class OptionalDoubleAdapter extends TypeAdapter { + private final TypeAdapter doubleAdapter; + + OptionalDoubleAdapter(TypeAdapter doubleAdapter) { + this.doubleAdapter = doubleAdapter; + } + + @Override + public OptionalDouble read(JsonReader in) throws IOException { + boolean isPresent = false; + double value = 0; + in.beginObject(); + while (in.hasNext()) { + String name = in.nextName(); + switch (name) { + case "isPresent": + isPresent = in.nextBoolean(); + break; + case "value": + // Delegate to the same Gson-configured adapter used for writing, so that + // round-trips stay symmetric when custom double adapters are registered. + Double readValue = doubleAdapter.read(in); + if (readValue != null) { + value = readValue; } - } - in.endObject(); - return isPresent ? OptionalDouble.of(value) : OptionalDouble.empty(); + break; + default: + in.skipValue(); } + } + in.endObject(); + return isPresent ? OptionalDouble.of(value) : OptionalDouble.empty(); + } - @Override - public void write(JsonWriter out, OptionalDouble value) throws IOException { - out.beginObject(); - out.name("isPresent"); - out.value(value.isPresent()); - out.name("value"); - // Note: in OpenJDK, OptionalDouble.EMPTY has value = Double.NaN, which causes - // ReflectiveTypeAdapterFactory to fail unless serializeSpecialFloatingPointValues() - // is enabled. Writing 0.0 when empty avoids that failure. - out.value(value.orElse(0)); - out.endObject(); - } - }.nullSafe(); + @Override + public void write(JsonWriter out, OptionalDouble value) throws IOException { + out.beginObject(); + out.name("isPresent"); + out.value(value.isPresent()); + out.name("value"); + // Delegate to the Gson-configured primitive double adapter, so that NaN and Infinity are + // rejected by default as they are for plain double values, and are only written when + // serializeSpecialFloatingPointValues() is enabled. Reading delegates to the same adapter. + // Note: in OpenJDK, OptionalDouble.EMPTY has value = Double.NaN; writing 0.0 when empty + // avoids that failure. + doubleAdapter.write(out, value.orElse(0)); + out.endObject(); + } + } } diff --git a/gson/src/test/java/com/google/gson/functional/JdkOptionalTest.java b/gson/src/test/java/com/google/gson/functional/JdkOptionalTest.java index a27b58efbd..b9a4e44dd5 100644 --- a/gson/src/test/java/com/google/gson/functional/JdkOptionalTest.java +++ b/gson/src/test/java/com/google/gson/functional/JdkOptionalTest.java @@ -17,6 +17,7 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -174,6 +175,104 @@ public void testOptionalDouble() { .isEqualTo(OptionalDouble.empty()); } + @Test + public void testOptionalDoubleSpecialValuesRejectedByDefault() { + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> gson.toJson(OptionalDouble.of(Double.NaN))); + assertThat(e) + .hasMessageThat() + .contains("NaN is not a valid double value as per JSON specification"); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(OptionalDouble.of(Double.POSITIVE_INFINITY))); + assertThrows( + IllegalArgumentException.class, + () -> gson.toJson(OptionalDouble.of(Double.NEGATIVE_INFINITY))); + } + + @Test + public void testOptionalDoubleSpecialValuesWhenEnabled() { + Gson specialValuesGson = new GsonBuilder().serializeSpecialFloatingPointValues().create(); + assertThat(specialValuesGson.toJson(OptionalDouble.of(Double.NaN))) + .isEqualTo("{\"isPresent\":true,\"value\":NaN}"); + assertThat(specialValuesGson.toJson(OptionalDouble.of(Double.POSITIVE_INFINITY))) + .isEqualTo("{\"isPresent\":true,\"value\":Infinity}"); + assertThat(specialValuesGson.toJson(OptionalDouble.of(Double.NEGATIVE_INFINITY))) + .isEqualTo("{\"isPresent\":true,\"value\":-Infinity}"); + Gson lenientSpecialValuesGson = + new GsonBuilder() + .serializeSpecialFloatingPointValues() + .setStrictness(Strictness.LENIENT) + .create(); + assertThat( + lenientSpecialValuesGson.fromJson( + specialValuesGson.toJson(OptionalDouble.of(Double.NaN)), OptionalDouble.class)) + .isEqualTo(OptionalDouble.of(Double.NaN)); + assertThat( + lenientSpecialValuesGson.fromJson( + specialValuesGson.toJson(OptionalDouble.of(Double.POSITIVE_INFINITY)), + OptionalDouble.class)) + .isEqualTo(OptionalDouble.of(Double.POSITIVE_INFINITY)); + assertThat( + lenientSpecialValuesGson.fromJson( + specialValuesGson.toJson(OptionalDouble.of(Double.NEGATIVE_INFINITY)), + OptionalDouble.class)) + .isEqualTo(OptionalDouble.of(Double.NEGATIVE_INFINITY)); + } + + @Test + public void testOptionalDoubleWithCustomBoxedDoubleAdapter() { + // OptionalDouble reads and writes through the Gson-configured double.class adapter, + // mirroring what ReflectiveTypeAdapterFactory does for a primitive double field. A custom + // adapter registered only for Double.class therefore does not apply, just as it does not + // apply to double fields or double[] elements. + TypeAdapter customAdapter = + new TypeAdapter() { + @Override + public Double read(JsonReader in) throws IOException { + throw new AssertionError("should not be called"); + } + + @Override + public void write(JsonWriter out, Double value) throws IOException { + throw new AssertionError("should not be called"); + } + }; + Gson boxedCustomGson = + new GsonBuilder().registerTypeAdapter(Double.class, customAdapter).create(); + assertThat(boxedCustomGson.toJson(OptionalDouble.of(41.0))) + .isEqualTo("{\"isPresent\":true,\"value\":41.0}"); + assertThat( + boxedCustomGson.fromJson("{\"isPresent\":true,\"value\":41.0}", OptionalDouble.class)) + .isEqualTo(OptionalDouble.of(41.0)); + } + + @Test + public void testOptionalDoubleWithCustomPrimitiveDoubleAdapter() { + // A custom adapter registered for double.class applies to reading and writing symmetrically. + TypeAdapter customAdapter = + new TypeAdapter() { + @Override + public Double read(JsonReader in) throws IOException { + return in.nextDouble() - 1; + } + + @Override + public void write(JsonWriter out, Double value) throws IOException { + out.value(value + 1); + } + }; + Gson primitiveCustomGson = + new GsonBuilder().registerTypeAdapter(double.class, customAdapter).create(); + assertThat(primitiveCustomGson.toJson(OptionalDouble.of(41.0))) + .isEqualTo("{\"isPresent\":true,\"value\":42.0}"); + assertThat( + primitiveCustomGson.fromJson( + "{\"isPresent\":true,\"value\":42.0}", OptionalDouble.class)) + .isEqualTo(OptionalDouble.of(41.0)); + } + @Test public void testCustomAdapterPrecedence() { TypeAdapter customAdapter =