Invalid JSON from Double.NaN as JsonObject property
- 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
Assessment
This issue has not been assessed yet.