Convert JObject into Dictionary. Is it possible?

前端 未结 5 843
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 03:35

I have a web API method that accepts an arbitrary json payload into a JObject property. As such I don\'t know what\'s coming but I still need to translate it to

5条回答
  •  太阳男子
    2020-12-08 04:24

    Here's the inception version: I've modified the code to recurse JArrays an JObjects nested in JArrays/JObjects, which the accepted answer does not, as pointed out by @Nawaz.

    using System.Collections.Generic;
    using System.Linq;
    using Newtonsoft.Json.Linq;
    
    public static class JsonConversionExtensions
    {
        public static IDictionary ToDictionary(this JObject json)
        {
            var propertyValuePairs = json.ToObject>();
            ProcessJObjectProperties(propertyValuePairs);
            ProcessJArrayProperties(propertyValuePairs);
            return propertyValuePairs;
        }
    
        private static void ProcessJObjectProperties(IDictionary 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(IDictionary 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]));
        }
    
        public static object[] ToArray(this JArray array)
        {
            return array.ToObject().Select(ProcessArrayEntry).ToArray();
        }
    
        private static object ProcessArrayEntry(object value)
        {
            if (value is JObject)
            {
                return ToDictionary((JObject) value);
            }
            if (value is JArray)
            {
                return ToArray((JArray) value);
            }
            return value;
        }
    }
    

提交回复
热议问题