{"id":"a6ab40277494b4dd","repo":"google/gson","slug":"json-forbids-nan-and-infinities-d-at-path-in","errorCode":null,"errorMessage":"JSON forbids NaN and infinities: {d}; at path {in.getPreviousPath()}","messagePattern":"JSON forbids NaN and infinities: (.+?); at path (.+?)","errorType":"exception","errorClass":"MalformedJsonException","httpStatus":null,"severity":"error","filePath":"gson/src/main/java/com/google/gson/ToNumberPolicy.java","lineNumber":88,"sourceCode":"    @Override\n    public Number readNumber(JsonReader in) throws IOException, JsonParseException {\n      String value = in.nextString();\n      if (value.indexOf('.') >= 0) {\n        return parseAsDouble(value, in);\n      } else {\n        try {\n          return Long.parseLong(value);\n        } catch (NumberFormatException e) {\n          return parseAsDouble(value, in);\n        }\n      }\n    }\n\n    private Number parseAsDouble(String value, JsonReader in) throws IOException {\n      try {\n        Double d = Double.valueOf(value);\n        if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {\n          throw new MalformedJsonException(\n              \"JSON forbids NaN and infinities: \" + d + \"; at path \" + in.getPreviousPath());\n        }\n        return d;\n      } catch (NumberFormatException e) {\n        throw new JsonParseException(\n            \"Cannot parse \" + value + \"; at path \" + in.getPreviousPath(), e);\n      }\n    }\n  },\n\n  /**\n   * Using this policy will ensure that numbers will be read as numbers of arbitrary length using\n   * {@link BigDecimal}.\n   */\n  BIG_DECIMAL {\n    @Override\n    public BigDecimal readNumber(JsonReader in) throws IOException {\n      String value = in.nextString();","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/google/gson/blob/8b8628c65699bc4421696183c62ae0c1b9b281dc/gson/src/main/java/com/google/gson/ToNumberPolicy.java#L70-L106","documentation":"In the LAZILY_PARSED_NUMBER (default) ToNumberPolicy, when a number literal parses to Double.NaN or Double.isInfinite() and the reader is not lenient, Gson throws MalformedJsonException. Standard JSON (RFC 8259) forbids NaN/Infinity, so non-lenient mode rejects them.","triggerScenarios":"JSON payload containing NaN, Infinity, -Infinity literals while the JsonReader strictness is not LENIENT; deserializing into double fields from non-spec-compliant producers (some JS encoders, older Java serializers).","commonSituations":"Interfacing with JavaScript JSON.stringify on non-finite numbers; legacy serializers that emit Infinity; strictness left at default (LEGACY_STRICT/STRICT).","solutions":["Set reader.setStrictness(Strictness.LENIENT) (or GsonBuilder via reflection) to accept non-finite values.","Sanitize the producer to emit null or a sentinel instead of NaN/Infinity.","Use a custom TypeAdapter<double> that maps null to NaN/0.","Validate the document with a regex/token check for NaN|Infinity before parsing if you must reject rather than accept."],"exampleFix":"// before\nGson gson = new Gson(); // default strictness rejects NaN\n\n// after\nGson gson = new GsonBuilder()\n    .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)\n    .create();\nJsonReader r = new JsonReader(reader);\nr.setStrictness(Strictness.LENIENT);","handlingStrategy":"validation","validationCode":"if (reader.getStrictness() != Strictness.LENIENT && sourceContainsNonFinite(json)) {\n  reader.setStrictness(Strictness.LENIENT);\n}\n","typeGuard":"boolean acceptsNonFinite(JsonReader r) {\n  return r.isLenient();\n}\n","tryCatchPattern":"try {\n  return policy.readNumber(in);\n} catch (MalformedJsonException ex) {\n  if (ex.getMessage().contains(\"NaN and infinities\")) {\n    in.setStrictness(Strictness.LENIENT); // or return null\n  }\n  throw ex;\n}\n","preventionTips":["Set LENIENT strictness when ingesting JS-produced JSON.","Sanitize producers to emit null instead of NaN/Infinity.","Document strictness assumptions in API contracts."],"tags":["deserialization","numbers","strictness","malformed-json"],"analyzedSha":"8b8628c65699bc4421696183c62ae0c1b9b281dc","analyzedAt":"2026-08-04T19:12:22.202Z","schemaVersion":2}