1. 程式人生 > >json擴展

json擴展

emp jobject ons pre urn arr param har ram

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;
        }
    }
}

  

json擴展