google / google/gson

Special FP values serialized without error when using JsonPrimitive (when this option is disabled)

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

Description

If the option to allow serialization of special floating-point values (`NaN`, `Infinity`) is disabled, `Gson` throws exception when serializing object that contains double fields with illegal values. But if JSON is constructed manually, through creation of `JsonPrimitive` instances with disallowed double values, non-compliant JSON is produced without reporting an error.
Consider the following example:

``` java
class DoubleHolder {
double number;
public DoubleHolder(double number) {
this.number = number;
}
}

void serialize() {
String s = new Gson().toJson(new DoubleHolder(0.0 / 0.0));
System.out.println(s);
}
```

This code properly produces the exception: `java.lang.IllegalArgumentException: NaN is not a valid double value as per JSON specification.`

But the following code:

``` java
void serialize() {
JsonObject jsonObject = new JsonObject();
jsonObject.add("number", new JsonPrimitive(0.0 / 0.0));
System.out.println(new Gson().toJson(jsonObject));
}
```

Somehow bypasses checks for `NaN` or `Infinity` and produces non-compliant JSON:

`{"number":NaN}`

This looks like a bug. In my opinion, `Gson` should produce the same results in these two cases. Or, if this behavior is expected, it should be described in `JsonPrimitive` API docs.

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.