mirror of
https://github.com/JogmansonReal/Radicade.git
synced 2026-10-25 23:18:56 -07:00
65 lines
1.5 KiB
C#
65 lines
1.5 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace RadicadeServer.Extensions
|
|
{
|
|
public static class JsonExtension
|
|
{
|
|
public static T? FromJson<T>(this string json)
|
|
{
|
|
return JsonSerializer.Deserialize<T>(json);
|
|
}
|
|
public static T? FromJson<T>(this string json, JsonSerializerOptions options)
|
|
{
|
|
return JsonSerializer.Deserialize<T>(json, options);
|
|
}
|
|
public static string ToJson(this object val)
|
|
{
|
|
return JsonSerializer.Serialize(val);
|
|
}
|
|
|
|
public static T Get<T>(this JsonNode node, string key, T fallback = default!)
|
|
{
|
|
try
|
|
{
|
|
var value = node?[key];
|
|
|
|
if (value is null)
|
|
return fallback;
|
|
|
|
if (value is JsonArray or JsonObject)
|
|
return value.Deserialize<T>() ?? fallback;
|
|
|
|
var kind = value.GetValueKind();
|
|
|
|
if (typeof(T) == typeof(bool))
|
|
{
|
|
if (kind == JsonValueKind.String)
|
|
{
|
|
var text = value.GetValue<string>();
|
|
return (T)(object)(text == "1" || text.Equals("true", StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
if (kind == JsonValueKind.Number)
|
|
return (T)(object)(value.GetValue<decimal>() != 0);
|
|
}
|
|
|
|
if (typeof(T).IsEnum)
|
|
{
|
|
if (kind == JsonValueKind.String)
|
|
return (T)Enum.Parse(typeof(T), value.GetValue<string>(), ignoreCase: true);
|
|
|
|
if (kind == JsonValueKind.Number)
|
|
return (T)Enum.ToObject(typeof(T), Convert.ChangeType(value.GetValue<decimal>(), Enum.GetUnderlyingType(typeof(T))));
|
|
}
|
|
|
|
return value.GetValue<T>();
|
|
}
|
|
catch
|
|
{
|
|
return fallback;
|
|
}
|
|
}
|
|
}
|
|
}
|