From 7a75328f0aed6a957a5890a6888af1a0c996f9c2 Mon Sep 17 00:00:00 2001 From: Anon Date: Thu, 26 Mar 2026 19:16:48 +0100 Subject: [PATCH] Fixed a JSON exception --- MinecraftClient/Json.cs | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/MinecraftClient/Json.cs b/MinecraftClient/Json.cs index da3aa838..08f5b24c 100644 --- a/MinecraftClient/Json.cs +++ b/MinecraftClient/Json.cs @@ -1,3 +1,4 @@ +using System; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; @@ -23,10 +24,46 @@ public static class Json public static JsonNode? ParseJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return null; + ReadOnlySpan text = json.AsSpan().TrimStart(); + if (!LooksLikeJson(text)) + return JsonValue.Create(json); + try { return JsonNode.Parse(json); } catch (JsonException) { return JsonValue.Create(json); } } + private static bool LooksLikeJson(ReadOnlySpan text) + { + if (text.IsEmpty) + return false; + + return text[0] switch + { + '{' or '"' => true, + '[' => LooksLikeJsonArray(text[1..]), + '-' => text.Length > 1 && char.IsAsciiDigit(text[1]), + >= '0' and <= '9' => true, + 't' or 'f' or 'n' => true, + _ => false + }; + } + + private static bool LooksLikeJsonArray(ReadOnlySpan text) + { + text = text.TrimStart(); + if (text.IsEmpty) + return false; + + return text[0] switch + { + ']' or '{' or '[' or '"' => true, + '-' => text.Length > 1 && char.IsAsciiDigit(text[1]), + >= '0' and <= '9' => true, + 't' or 'f' or 'n' => true, + _ => false + }; + } + /// /// Escape a string for embedding inside a JSON string literal. /// Uses System.Text.Json serialization and strips the surrounding quotes. @@ -52,4 +89,4 @@ public static class JsonNodeExtensions JsonValue val when val.TryGetValue(out var s) => s, _ => node.ToJsonString() }; -} \ No newline at end of file +}