Files
sbox-public/engine/Sandbox.System/Extend/JsonExtensions.cs
s&box team 71f266059a Open source release
This commit imports the C# engine code and game files, excluding C++ source code.

[Source-Commit: ceb3d758046e50faa6258bc3b658a30c97743268]
2025-11-24 09:05:18 +00:00

44 lines
764 B
C#

using System.Text.Json.Nodes;
namespace Sandbox;
public static partial class SandboxSystemExtensions
{
/// <summary>
/// Get a property value by name, from a JsonObject. Return defaultValue if it's not found.
/// </summary>
public static T GetPropertyValue<T>( this JsonObject jso, string membername, in T defaultvalue )
{
if ( jso is null )
return defaultvalue;
if ( !jso.TryGetPropertyValue( membername, out var value ) )
return defaultvalue;
if ( value is T tValue )
return tValue;
if ( value is JsonNode node )
{
try
{
return node.Deserialize<T>();
}
catch
{
return defaultvalue;
}
}
try
{
return (T)Convert.ChangeType( value, typeof( T ) );
}
catch
{
return defaultvalue;
}
}
}