Innovenergy_trunk/csharp/Lib/Utils/JsonNodeAccessors.cs

66 lines
2.4 KiB
C#
Raw Normal View History

using System.Diagnostics.CodeAnalysis;
2023-02-16 12:57:06 +00:00
using System.Text.Json.Nodes;
2023-05-11 08:20:47 +00:00
using System.Text.Json.Serialization;
2023-02-16 12:57:06 +00:00
namespace InnovEnergy.Lib.Utils;
public static class JsonNodeAccessors
{
public static T Get<T>(this JsonNode n, String propName) => n[propName]!.GetValue<T>();
2023-02-16 12:57:06 +00:00
public static String? GetString(this JsonNode n, String propName) => n.TryGetString(propName);
2023-02-16 12:57:06 +00:00
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)
2023-05-11 08:20:47 +00:00
{
try
{
return n.TryGet<String>(propName) ?? "";
2023-05-11 08:20:47 +00:00
}
catch (Exception e)
{
Console.WriteLine(e);
return n.TryGet<UInt64>(propName).ToString();
}
}
2023-02-16 12:57:06 +00:00
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();
}