Skip to content

Commit

Permalink
xvalue support jsonelement
Browse files Browse the repository at this point in the history
  • Loading branch information
nameofSEOKWONHONG committed Oct 22, 2024
1 parent a9a3187 commit 5406525
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/XValueExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ namespace eXtensionSharp
public static class XValueExtensions
{
/// <summary>
/// object to T value
/// object to T value,
/// </summary>
/// <remarks>
/// 10-22-24 : support json element, support value kind type is string, number, true, false, null, undefined
/// </remarks>
/// <typeparam name="T"></typeparam>
/// <param name="src"></param>
/// <param name="default"></param>
Expand Down Expand Up @@ -36,6 +39,11 @@ public static T xValue<T>(this object src, object @default = null)
return (T)src;
}

if (src is JsonElement t)
{
return t.JsonElementToValue<T>();
}

//if (typeof(T).xIsNumber())
//{
// if (typeof(T).GetType() == typeof(byte)) return (T)(object)Convert.ToByte(src);
Expand Down Expand Up @@ -65,6 +73,22 @@ public static T xValue<T>(this object src, object @default = null)
return (T)Convert.ChangeType(src, typeof(T));
}

private static T JsonElementToValue<T>(this JsonElement element)
{
var v = element.ValueKind switch
{
JsonValueKind.String => element.GetString().xValue<T>(),
JsonValueKind.Number => element.GetDouble().xValue<T>(),
JsonValueKind.True => element.GetBoolean().xValue<T>(),
JsonValueKind.False => element.GetBoolean().xValue<T>(),
JsonValueKind.Null => default,
JsonValueKind.Undefined => default,
_ => throw new Exception($"Unexpected JsonValueKind {element.ValueKind}")
};

return v;
}

/// <summary>
/// casting src to T (hard casting)
/// </summary>
Expand Down

0 comments on commit 5406525

Please sign in to comment.