{"record":{"id":"895928810efd686c","repo":"dotnet/BenchmarkDotNet","slug":"unexpected-token-reader-tokentype-when-parsing-f","errorCode":null,"errorMessage":"Unexpected token {reader.TokenType} when parsing float.","messagePattern":"Unexpected token (.+?) when parsing float\\.","errorType":"exception","errorClass":"JsonException","httpStatus":null,"severity":"error","filePath":"src/BenchmarkDotNet/Serialization/BdnSimpleJsonSerializer.cs","lineNumber":53,"sourceCode":"    public static string Serialize<T>(T item, bool indentJson = false)\n    {\n        if (indentJson)\n            return JsonSerializer.Serialize(item, IndentedOptions);\n        else\n            return JsonSerializer.Serialize(item, DefaultOptions);\n    }\n\n    /// <summary>\n    /// Custom JsonConverter for float that write Nan/PositiveInfinite/NegativeInfinite as empty string.\n    /// </summary>\n    private class SimpleJsonFloatConverter : JsonConverter<float>\n    {\n        public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n        {\n            if (reader.TokenType == JsonTokenType.Number)\n                return reader.GetSingle();\n\n            throw new JsonException($\"Unexpected token {reader.TokenType} when parsing float.\");\n        }\n\n        public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options)\n        {\n            if (float.IsNaN(value) || float.IsInfinity(value))\n                writer.WriteStringValue(\"\");\n            else\n                writer.WriteNumberValue(value);\n        }\n    }\n\n    /// <summary>\n    /// Custom JsonConverter for double that write Nan/PositiveInfinite/NegativeInfinite as empty string.\n    /// </summary>\n    private class SimpleJsonDoubleConverter : JsonConverter<double>\n    {\n        public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n        {","sourceCodeStart":35,"sourceCodeEnd":71,"githubUrl":"https://github.com/dotnet/BenchmarkDotNet/blob/b515068b61ad1c9c9aa938b8ece4af1e7d6d85a3/src/BenchmarkDotNet/Serialization/BdnSimpleJsonSerializer.cs#L35-L71","documentation":"Thrown by SimpleJsonFloatConverter.Read during JSON deserialization when the token at the current position is not a JsonTokenType.Number. The custom converter handles the serialization of float.NaN, float.PositiveInfinity, and float.NegativeInfinity by writing them as empty strings, but on read it only accepts numeric tokens. Any non-number token (including the empty string written for NaN/Infinity) triggers this JsonException.","triggerScenarios":"Deserializing JSON that contains a float field encoded as a string (including the empty string that the Write method uses for NaN/Infinity), a null token, or a property name where a number is expected. The mismatch between Write (which can emit empty strings) and Read (which rejects them) means round-tripping NaN/Infinity values through this serializer will fail on read.","commonSituations":"Exporting benchmark results containing NaN or Infinity statistics to JSON via BdnSimpleJsonSerializer, then trying to re-import them. Reading JSON from an external source that represents floats as strings.","solutions":["If round-tripping NaN/Infinity is needed, the converter's Read method must handle string tokens (including empty string) — this may require a custom converter override or a library fix.","Ensure the JSON being deserialized was produced by a serializer that writes floats as JSON numbers, not strings.","Filter or sanitize NaN/Infinity values from statistics before serialization if re-import is required."],"exampleFix":"// The converter's Read only accepts numbers:\nif (reader.TokenType == JsonTokenType.Number)\n    return reader.GetSingle();\nthrow new JsonException(...);\n\n// To handle round-tripped NaN/Infinity (empty string),\n// a fix would extend Read:\n// if (reader.TokenType == JsonTokenType.String)\n//     return float.NaN; // or parse appropriately","handlingStrategy":"validation","validationCode":"// Before deserializing, check if JSON contains string-encoded floats\nusing var doc = JsonDocument.Parse(jsonString);\nforeach (var prop in doc.RootElement.EnumerateObject())\n    if (prop.Value.ValueKind == JsonValueKind.String && prop.Name.Contains(\"float\", StringComparison.OrdinalIgnoreCase))\n        throw new InvalidOperationException(\"JSON contains string-encoded float values that cannot be deserialized by BdnSimpleJsonSerializer.\");","typeGuard":null,"tryCatchPattern":"try\n{\n    var result = JsonSerializer.Deserialize<MyModel>(json, BdnSimpleJsonSerializer.Options);\n}\ncatch (JsonException ex) when (ex.Message.Contains(\"parsing float\"))\n{\n    // The float was serialized as a string (NaN/Infinity). Use default System.Text.Json options instead.\n    var result = JsonSerializer.Deserialize<MyModel>(json);\n}","preventionTips":["For JSON that needs round-tripping, use System.Text.Json's default options instead of BdnSimpleJsonSerializer.","Sanitize NaN/Infinity values from statistics before serializing if re-import is needed.","Be aware that BdnSimpleJsonSerializer's Write and Read are asymmetric for special float values."],"tags":["serialization","json","float","json-exception"],"backgroundTag":null,"analyzedSha":"b515068b61ad1c9c9aa938b8ece4af1e7d6d85a3","analyzedAt":"2026-08-13T19:12:24.196Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}