Json扩展方法

命名空间:

点击查看代码
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;
        }




    }
posted on 2024-03-23 17:55  RookieBoy666  阅读(8)  评论(0编辑  收藏  举报