Files
KJD/AllBase/Extension/JTokenExtension.cs
2025-06-29 19:38:31 +08:00

36 lines
913 B
C#

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AllBase.Extension
{
public static class JTokenExtension
{
public static T ToValue<T>(this JToken token, T defValue = default(T))
{
string tempvalue = token.ToString();
if (string.IsNullOrEmpty(tempvalue))
return defValue;
Type type = typeof(T);
var typeName = type.Name.ToLower();
try
{
if (typeName == "string")
return (T)(object)tempvalue;
if (tempvalue is IConvertible)
return (T)System.Convert.ChangeType(tempvalue, type);
}
catch
{
return default(T);
}
return defValue;
}
}
}