36 lines
913 B
C#
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;
|
|
}
|
|
}
|
|
}
|