Innovenergy_trunk/csharp/Lib/Utils/JsonNodeAccessors.cs

52 lines
2.1 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
using System.Text.Json.Nodes;
namespace InnovEnergy.Lib.Utils;
public static class JsonNodeAccessors
{
public static T Get<T>(this JsonNode n, String propName) => n[propName]!.GetValue<T>();
public static String GetString(this JsonNode n, String propName) => n.Get<String>(propName);
public static Boolean GetBoolean(this JsonNode n, String propName) => n.Get<Boolean>(propName);
public static UInt32 GetUInt32(this JsonNode n, String propName) => n.Get<UInt32>(propName);
public static UInt64 GetUInt64(this JsonNode n, String propName) => n.Get<UInt64>(propName);
public static Int32 GetInt32(this JsonNode n, String propName) => n.Get<Int32>(propName);
public static Int64 GetInt64(this JsonNode n, String propName) => n.Get<Int64>(propName);
public static JsonArray GetArray(this JsonNode n, String propName) => n[propName]!.AsArray();
public static T[] GetArray<T>(this JsonNode n, String propName) => n.GetArray(propName)
.Select(e => e!.GetValue<T>())
.ToArray();
public static T? TryGet<T>(this JsonNode n, String propName)
{
try
{
return n[propName]!.GetValue<T>();
}
catch
{
return default;
}
}
public static String? TryGetString(this JsonNode n, String propName) => n.TryGet<String>(propName);
public static Boolean? TryGetBoolean(this JsonNode n, String propName) => n.TryGet<Boolean>(propName);
public static UInt32? TryGetUInt32(this JsonNode n, String propName) => n.TryGet<UInt32>(propName);
public static UInt64? TryGetUInt64(this JsonNode n, String propName) => n.TryGet<UInt64>(propName);
public static Int32? TryGetInt32(this JsonNode n, String propName) => n.TryGet<Int32>(propName);
public static Int64? TryGetInt64(this JsonNode n, String propName) => n.TryGet<Int64>(propName);
public static JsonArray? TryGetArray(this JsonNode n, String propName) => n[propName]?.AsArray();
}