diff --git a/Solutions/Corvus.Json.ExtendedTypes/Corvus.Json/JsonValueExtensions.cs b/Solutions/Corvus.Json.ExtendedTypes/Corvus.Json/JsonValueExtensions.cs index 19ea4810a..4a3fed7e7 100644 --- a/Solutions/Corvus.Json.ExtendedTypes/Corvus.Json/JsonValueExtensions.cs +++ b/Solutions/Corvus.Json.ExtendedTypes/Corvus.Json/JsonValueExtensions.cs @@ -3,6 +3,7 @@ // using System.Buffers; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text; @@ -16,6 +17,50 @@ namespace Corvus.Json; /// public static class JsonValueExtensions { + /// + /// Gets a property. + /// + /// The type of the from which to get the property. + /// The type of the result. + /// The type of the string containing the name. + /// The instance of the from which to get the property. + /// The name of the property. + /// The resulting property, if any. + /// if the property exists. + public static bool TryGetProperty(this T jsonObject, in TString name, out TValue property) + where T : struct, IJsonObject + where TValue : struct, IJsonValue + where TString : struct, IJsonString + { + Debug.Assert(name.IsValid(), $"The string must be a valid {name.GetType().Name}"); + + if (name.HasDotnetBacking) + { + return jsonObject.TryGetProperty((string)name, out property); + } + else + { + if (jsonObject.HasDotnetBacking) + { + return name.TryGetValue(TryGetString, jsonObject, out property); + } + else + { + return name.TryGetValue(TryGetStringUtf8, jsonObject, out property); + } + } + + static bool TryGetString(ReadOnlySpan span, in T state, out TValue value) + { + return state.TryGetProperty(span, out value); + } + + static bool TryGetStringUtf8(ReadOnlySpan span, in T state, out TValue value) + { + return state.TryGetProperty(span, out value); + } + } + /// /// Clones an to enable it to be /// used safely outside of its construction context.