google / google/gson

Non-lenient JsonWriter.value for NaN or Infinity writes name before throwing exception

Open
#1,736 0 comments 1 reaction 0 assignees View on GitHub
bug
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

For a non-lenient JsonWriter the methods `value(double)` and `value(Number)` write the name of the current JSON property before checking if the value is valid and throwing an exception.

This is problematic for JsonWriters which are supposed to not serialize properties with `null` values (`setSerializeNulls(false)`):
```java
public void testSerializeNulls() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setSerializeNulls(false);
jsonWriter.beginObject();

// Make sure that methods throwing exceptions do not write
// name
jsonWriter.name("test");
try {
// value(double)
jsonWriter.value(Double.NaN);
} catch (IllegalArgumentException expected) {
}
jsonWriter.nullValue();

jsonWriter.endObject();
// Fails because `test:null` has been written
assertEquals("{}", stringWriter.toString());
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.