json扩展

时间:2024-07-09 22:35:56
using Newtonsoft.Json.Linq;

namespace Utility
{
public static class JsonExt
{
/// <summary>
/// 转换为JObject对象
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static JObject ToJObject(this string str)
{
JObject j = new JObject();
try
{
j = JObject.Parse(str);
}
catch
{
}
return j;
} /// <summary>
/// 转换为JArray对象
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static JArray ToJArray(this string str)
{
JArray j = new JArray();
try
{
j = JArray.Parse(str);
}
catch
{
}
return j;
} /// <summary>
/// 根据键获取值
/// </summary>
/// <param name="jo"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string JValue(this JObject jo, string key)
{
string val = string.Empty;
try
{
val = jo[key].ToString();
}
catch
{
}
return val;
} /// <summary>
/// 检查JObject是否含有指定key值
/// </summary>
/// <param name="jo"></param>
/// <param name="key"></param>
/// <returns></returns>
public static bool CheckKey(this JObject jo, string key)
{
if (jo != null && jo.Count > 0)
if (jo.Property(key) != null)
return true;
return false;
}
}
}