Convert JObject into Dictionary. Is it possible?

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

    Here is a simpler version:

        public static object ToCollections(object o)
        {
            var jo = o as JObject;
            if (jo != null) return jo.ToObject>().ToDictionary(k => k.Key, v => ToCollections(v.Value));
            var ja = o as JArray;
            if (ja != null) return ja.ToObject>().Select(ToCollections).ToList();
            return o;
        }
    

    If using C# 7 we can use pattern matching where it would look like this:

        public static object ToCollections(object o)
        {
            if (o is JObject jo) return jo.ToObject>().ToDictionary(k => k.Key, v => ToCollections(v.Value));
            if (o is JArray ja) return ja.ToObject>().Select(ToCollections).ToList();
            return o;
        }
    

提交回复
热议问题