google / google/gson

Invalid JSON from Double.NaN as JsonObject property

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

Description

Double.NaN as JsonObject property generates invalid JSON and does not throw exception
This is with 2.8.2
Code fragment:
```java
final Gson gson = new GsonBuilder().serializeNulls().create();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("invalidDouble", Double.NaN);
JsonElement jsonElement = jsonObject;
log("As property within object: " + jsonElement.toString()); // expect this to throw exception
jsonElement = new JsonPrimitive(Double.NaN);
log("As primitive: " + jsonElement.toString()); // expect this to throw exception
jsonElement = gson.toJsonTree(Double.NaN);
log("As raw value toJsonTree: " + jsonElement.toString()); // this throws exception, as expected
```
Output:
```
As property within object: {"invalidDouble":NaN}
As primitive: NaN
Exception in thread "main" java.lang.IllegalArgumentException: NaN is not a valid double value as per JSON specification. To override this behavior, use GsonBuilder.serializeSpecialFloatingPointValues() method.
at com.google.gson.Gson.checkValidFloatingPoint(Gson.java:324)
at com.google.gson.Gson$1.write(Gson.java:292)
at com.google.gson.Gson$1.write(Gson.java:278)
at com.google.gson.Gson.toJson(Gson.java:669)
at com.google.gson.Gson.toJsonTree(Gson.java:562)
at com.google.gson.Gson.toJsonTree(Gson.java:541)
```

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.