google / google/gson

Serialize special floating point values as string's

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

Description

When using GsonBuilder#serializeSpecialFloatingPointValues() to enable output of NaN and Infinity floating point values, the generated JSON string look like '{"propName":NaN}'.

Many JSON libraries used with REST usually generates the special values encoded as strings like in '{"propName":"NaN"}'.

This changes the type of the value but it has the advantage that the result is still a valid JSON string that can be parsed by ECMAScript function JSON.parse in most browsers, avoiding the need for eval() with the tokens in the global scope.

Both strings already can be deserialized by Gson in the lenient mode.

This approach can actually be achieved by overriding the type adapters for float, double and Number replacing the TypeAdapter write function with code below, but it would be nice to have a pre-configured GsonBuilder#serializeSpecialFloatingPointValuesAsString() option ready to use in the library.

```
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
double dval = value.doubleValue();
if (Double.isNaN(dval) || Double.isInfinite(dval)) {
String sval = value.toString();
out.value(sval);
return;
}
out.value(value);
}
```

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.