Minecraft-Console-Client/MinecraftClient/Json.cs
copilot-swe-agent[bot] d2c1cbf2a5 Fix Json.ParseJson crash on empty/null input
ParseJson now returns null for null, empty, or whitespace-only input
instead of throwing JsonReaderException. This matches the behavior of
the old hand-rolled parser and is needed because MC protocol packets
may contain empty strings where JSON text is expected (e.g. empty chat
messages in DeathCombatEvent packets).

Discovered during end-to-end testing against a Minecraft 1.21.11
protocol server.

Co-authored-by: milutinke <441903+milutinke@users.noreply.github.com>
Agent-Logs-Url: https://github.com/milutinke/Minecraft-Console-Client/sessions/34df723e-4a63-45a0-a942-e119d81a575b
2026-03-22 17:22:08 +00:00

49 lines
No EOL
1.6 KiB
C#

using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace MinecraftClient;
/// <summary>
/// JSON utilities backed by System.Text.Json.
/// </summary>
public static class Json
{
private static readonly JsonSerializerOptions s_escapeOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
/// <summary>
/// Parse a JSON string into a mutable <see cref="JsonNode"/> DOM.
/// Returns null for null, empty, or whitespace-only input.
/// </summary>
public static JsonNode? ParseJson(string? json) =>
string.IsNullOrWhiteSpace(json) ? null : JsonNode.Parse(json);
/// <summary>
/// Escape a string for embedding inside a JSON string literal.
/// Uses System.Text.Json serialization and strips the surrounding quotes.
/// </summary>
public static string EscapeString(string src) =>
JsonSerializer.Serialize(src, s_escapeOptions)[1..^1];
}
/// <summary>
/// Extension helpers for <see cref="JsonNode"/> that replicate the access patterns
/// of the former <c>JSONData.StringValue</c> property.
/// </summary>
public static class JsonNodeExtensions
{
/// <summary>
/// Return the string representation of any JSON value.
/// Strings are returned without quotes; numbers, booleans, and null
/// are returned as their text representation.
/// </summary>
public static string GetStringValue(this JsonNode? node) => node switch
{
null => "null",
JsonValue val when val.TryGetValue<string>(out var s) => s,
_ => node.ToJsonString()
};
}