mirror of
https://github.com/MCCTeam/Minecraft-Console-Client
synced 2026-08-15 13:04:36 +00:00
Fixed a JSON exception
This commit is contained in:
parent
747662ea8c
commit
7a75328f0a
1 changed files with 38 additions and 1 deletions
|
|
@ -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<char> 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<char> 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<char> 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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<string>(out var s) => s,
|
||||
_ => node.ToJsonString()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue