Convert JObject into Dictionary. Is it possible?

前端 未结 5 850
没有蜡笔的小新
没有蜡笔的小新 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

    I ended up using a mix of both answers as none really nailed it.

    ToObject() can do the first level of properties in a JSON object, but nested objects won't be converted to Dictionary().

    There's also no need to do everything manually as ToObject() is pretty good with first level properties.

    Here is the code:

    public static class JObjectExtensions
    {
        public static IDictionary ToDictionary(this JObject @object)
        {
            var result = @object.ToObject>();
    
            var JObjectKeys = (from r in result
                               let key = r.Key
                               let value = r.Value
                               where value.GetType() == typeof(JObject)
                               select key).ToList();
    
            var JArrayKeys = (from r in result
                              let key = r.Key
                              let value = r.Value
                              where value.GetType() == typeof(JArray)
                              select key).ToList();
    
            JArrayKeys.ForEach(key => result[key] = ((JArray)result[key]).Values().Select(x => ((JValue)x).Value).ToArray());
            JObjectKeys.ForEach(key => result[key] = ToDictionary(result[key] as JObject));
    
            return result;
        }
    }
    

    It might have edge cases where it won't work and the performance is not the strongest quality of it.

    Thanks guys!

提交回复
热议问题