2026-03-22 16:39:26 +00:00
|
|
|
using System.Text.Encodings.Web;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Nodes;
|
2015-06-19 19:29:23 +02:00
|
|
|
|
2026-03-22 16:39:26 +00:00
|
|
|
namespace MinecraftClient;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// JSON utilities backed by System.Text.Json.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class Json
|
2015-06-19 19:29:23 +02:00
|
|
|
{
|
2026-03-22 16:39:26 +00:00
|
|
|
private static readonly JsonSerializerOptions s_escapeOptions = new()
|
2015-06-19 19:29:23 +02:00
|
|
|
{
|
2026-03-22 16:39:26 +00:00
|
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
|
|
|
};
|
2023-05-27 19:46:28 +02:00
|
|
|
|
2026-03-22 16:39:26 +00:00
|
|
|
/// <summary>
|
|
|
|
|
/// Parse a JSON string into a mutable <see cref="JsonNode"/> DOM.
|
2026-03-22 17:22:08 +00:00
|
|
|
/// Returns null for null, empty, or whitespace-only input.
|
2026-03-22 19:53:15 +01:00
|
|
|
/// Returns a <see cref="JsonValue"/> wrapping the raw string when the input
|
|
|
|
|
/// is not valid JSON (e.g. a plain-text Minecraft MOTD or chat message).
|
2026-03-22 16:39:26 +00:00
|
|
|
/// </summary>
|
2026-03-22 19:53:15 +01:00
|
|
|
public static JsonNode? ParseJson(string? json)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrWhiteSpace(json)) return null;
|
|
|
|
|
try { return JsonNode.Parse(json); }
|
|
|
|
|
catch (JsonException) { return JsonValue.Create(json); }
|
|
|
|
|
}
|
2023-05-27 19:46:28 +02:00
|
|
|
|
2026-03-22 16:39:26 +00:00
|
|
|
/// <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()
|
|
|
|
|
};
|
2023-05-27 19:46:28 +02:00
|
|
|
}
|