Json擴充套件方法

RookieBoy666發表於2024-03-23

名稱空間:

點選檢視程式碼
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;

類:

點選檢視程式碼
   /// <summary>
    /// Json擴充套件方法
    /// </summary>
    public static class JsonExtends
    {
        private static LogHelper Log { get; } = new LogHelper("JsonExtends");

        public static T ToEntity<T>(this string val)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(val);
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                return default(T);
            }
        }

        //public static List<T> ToEntityList<T>(this string val)
        //{
        //    return JsonConvert.DeserializeObject<List<T>>(val);
        //}
        public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
        {
            try
            {
                return JsonConvert.SerializeObject(entity, formatting);
            }
            catch (Exception ex)
            {
                //Log.Error(ex);

                return string.Empty;
            }

        }

        /// <summary>
        /// Json 格式化
        /// </summary>
        /// <param name="jsonStr">未格式化的Json字串</param>
        /// <returns>格式化後的Json字串</returns>
        public static string JsonFormatOut(this string jsonStr)
        {
            //格式化json字串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(jsonStr);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return jsonStr;
            }
        }
        /// <summary>
        /// 透過Json資料中的key獲取對應的Value 重名的獲取第一個
        /// </summary>
        /// <typeparam name="T">所獲取資料的資料型別</typeparam>
        /// <param name="jObject">JObject物件</param>
        /// <param name="key">key</param>
        /// <returns>key對應的Value  沒有找到時返回null</returns>
        public static T GetValueByKey<T>(this JObject jObject, string key)
        {
            var tempValue = jObject.GetValue(key);
            if (tempValue != null)
            {
                return tempValue.Value<T>();
            }
            else
            {
                var enumerator = jObject.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (enumerator.Current.Value.HasValues)
                    {
                        if (enumerator.Current.Value is JObject)
                        {
                            T tempTValue = GetValueByKey<T>(enumerator.Current.Value as JObject, key);
                            if (tempTValue != null)
                            {
                                return tempTValue;
                            }
                        }
                        else if (enumerator.Current.Value is JArray)
                        {
                            JArray arrayObj = enumerator.Current.Value as JArray;
                            T tempTValue = GetValueByKey<T>(arrayObj as JArray, key);
                            if (tempTValue != null)
                            {
                                return tempTValue;
                            }
                        }
                    }
                }
            }

            return default(T);
        }

        /// <summary>
        /// 透過Json資料中的key獲取對應的Value 重名的獲取第一個
        /// </summary>
        /// <typeparam name="T">所獲取資料的資料型別</typeparam>
        /// <param name="jObject">JObject物件</param>
        /// <param name="key">key</param>
        /// <returns>key對應的Value  沒有找到時返回null</returns>
        public static T GetValueByKey<T>(this JToken jObject, string key)
        {
            var propChildren = jObject.Children().Cast<JProperty>();
            var matchProp = propChildren.FirstOrDefault(p => p.Name == key);
            if (matchProp != null)
            {
                return jObject.Value<T>(key);
            }

            return default(T);
        }


        /// <summary>
        /// 判斷JToken中是否包含對應的欄位或屬性
        /// </summary>
        /// <param name="jToken">JToken  對應</param>
        /// <param name="peropertyName">欄位或屬性名稱</param>
        /// <returns></returns>
        public static bool IsContainProp(this JToken jToken, string peropertyName)
        {
            var propChildren = jToken.Children().Cast<JProperty>();
            var matchProp = propChildren.FirstOrDefault(p => p.Name == peropertyName);
            if (matchProp != null)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 判斷JObject中是否包含對應的欄位或屬性
        /// </summary>
        /// <param name="jObject">JToken  對應</param>
        /// <param name="peropertyName">欄位或屬性名稱</param>
        /// <returns></returns>
        public static bool IsContainProp(this JObject jObject, string peropertyName)
        {
            var propChildren = jObject.Children().Cast<JProperty>();
            var matchProp = propChildren.FirstOrDefault(p => p.Name == peropertyName);
            if (matchProp != null)
            {
                return true;
            }

            return false;
        }




    }

相關文章