Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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 @@ -62,7 +62,10 @@ public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> 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")
Expand Down Expand Up @@ -177,41 +180,53 @@ public void write(JsonWriter out, OptionalLong value) throws IOException {
}
}.nullSafe();

private static final TypeAdapter<OptionalDouble> OPTIONAL_DOUBLE =
new TypeAdapter<OptionalDouble>() {
@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<OptionalDouble> {
private final TypeAdapter<Double> doubleAdapter;

OptionalDoubleAdapter(TypeAdapter<Double> 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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delegating write() to gson.getAdapter(Double.class) while read() still calls in.nextDouble() makes round-tripping asymmetric whenever a custom TypeAdapter<Double> is registered on GsonBuilder (writes go through the custom adapter, reads bypass it). Also, ReflectiveTypeAdapterFactory resolves the underlying double field with double.class rather than Double.class. If custom adapters are meant to apply here, read() should delegate to the same double.class adapter (guarding against null); otherwise, checking serializeSpecialFloatingPointValues directly avoids routing OptionalDouble through unrelated custom Double adapters.

out.endObject();
}
}
}
99 changes: 99 additions & 0 deletions gson/src/test/java/com/google/gson/functional/JdkOptionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Double> customAdapter =
new TypeAdapter<Double>() {
@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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a suggestion: Could alternatively for read and write do something like throw new AssertionError("should not be called").

That might make the intention even clearer.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in d444349 - the Double.class stubs now throw AssertionError("should not be called"). Kept the real +/- 1 transforms in the double.class test below, since there the registered adapter is expected to be invoked.

}
};
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<Double> customAdapter =
new TypeAdapter<Double>() {
@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<OptionalInt> customAdapter =
Expand Down