蔚蓝触点 Azuretouch

Azuretouch
Touch your future

JObject的扩展,转换成字典类型

这里记录一个 Newtonsoft.Json 的扩展,可以将 JObject 直接转换为字典类型 Dictionary<string, object>
使用方法为

Dictionary<string, object> json = JsonConvert.DeserializeObject<JToken>(content).ToDictionary();

或者

Dictionary<string, object> json = JToken.Parse(content).ToDictionary();


详细代码如下

    /// <summary>
    /// JObject扩展
    /// </summary>
    public static class JObjectExtensions
    {
        /// <summary>
        /// 将JObject转化成字典
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ToDictionary(this JToken json)
        {
            var propertyValuePairs = json.ToObject<Dictionary<string, object>>();
            ProcessJObjectProperties(propertyValuePairs);
            ProcessJArrayProperties(propertyValuePairs);
            return propertyValuePairs;
        }

        private static void ProcessJObjectProperties(Dictionary<string, object> propertyValuePairs)
        {
            var objectPropertyNames = (from property in propertyValuePairs
                                       let propertyName = property.Key
                                       let value = property.Value
                                       where value is JObject
                                       select propertyName).ToList();

            objectPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToDictionary((JObject)propertyValuePairs[propertyName]));
        }

        private static void ProcessJArrayProperties(Dictionary<string, object> propertyValuePairs)
        {
            var arrayPropertyNames = (from property in propertyValuePairs
                                      let propertyName = property.Key
                                      let value = property.Value
                                      where value is JArray
                                      select propertyName).ToList();

            arrayPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToArray((JArray)propertyValuePairs[propertyName]));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static ArrayList ToArray(this JArray array)
        {
            object[] list = array.ToObject<object[]>().Select(ProcessArrayEntry).ToArray();
            return new ArrayList(list);
        }

        private static object ProcessArrayEntry(object value)
        {
            if (value is JObject)
            {
                return ToDictionary((JObject)value);
            }
            if (value is JArray)
            {
                return ToArray((JArray)value);
            }
            return value;
        }

    }
未经允许不得转载:蔚蓝触点 Azuretouch » JObject的扩展,转换成字典类型

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址