Convert JObject into Dictionary. Is it possible?

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

    Sounds like a good use case for extension methods - I had something lying around that was pretty straightforward to convert to Json.NET (Thanks NuGet!):

    Of course, this is quickly hacked together - you'd want to clean it up, etc.

    public static class JTokenExt
    {
        public static Dictionary 
             Bagify(this JToken obj, string name = null)
        {
            name = name ?? "obj";
            if(obj is JObject)
            {
                var asBag =
                    from prop in (obj as JObject).Properties()
                    let propName = prop.Name
                    let propValue = prop.Value is JValue 
                        ? new Dictionary()
                            {
                                {prop.Name, prop.Value}
                            } 
                        :  prop.Value.Bagify(prop.Name)
                    select new KeyValuePair(propName, propValue);
                return asBag.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            }
            if(obj is JArray)
            {
                var vals = (obj as JArray).Values();
                var alldicts = vals
                    .SelectMany(val => val.Bagify(name))
                    .Select(x => x.Value)
                    .ToArray();
                return new Dictionary()
                { 
                    {name, (object)alldicts}
                };
            }
            if(obj is JValue)
            {
                return new Dictionary()
                { 
                    {name, (obj as JValue)}
                };
            }
            return new Dictionary()
            { 
                {name, null}
            };
        }
    }
    

提交回复
热议问题