转换成JObject&字典LT;字符串对象&gt ;.是否可以? [英] Convert JObject into Dictionary<string, object>. Is it possible?

查看:851
本文介绍了转换成JObject&字典LT;字符串对象&gt ;.是否可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须接受一个任意JSON的有效载荷送入一个J​​Object属性的Web API方法。因此我不知道将会发生什么,但我仍然需要将其翻译为.NET类型。我想有一个解释,所以我可以对付它反正我想。

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 .NET types. I would like to have a Dictionary so I can deal with it anyway I want to.

我搜索了很多,但找不到什么,最终开始凌乱方法是由价值做这种转换,关键靠键,值。有没有一种简单的方法来做到这一点。

I searched a lot, but couldn't find nothing and ended up starting a messy method to do this conversion, key by key, value by value. Is there a easy way to do it?

输入 - >

JObject person = new JObject(
    new JProperty("Name", "John Smith"),
    new JProperty("BirthDate", new DateTime(1983, 3, 20)),
    new JProperty("Hobbies", new JArray("Play footbal", "Programming")),
    new JProperty("Extra", new JObject(
        new JProperty("Foo", 1),
        new JProperty("Bar", new JArray(1, 2, 3))
    )
)

谢谢!

推荐答案

我结束了使用这两种答案的组合作为没有人真的钉它

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

ToObject()可以做一个JSON对象属性的第一级,但嵌套的对象将不能转换为词典()。

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

还有没有必要做一切手动为ToObject()是第一级性能相当不错

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

下面是代码:

public static class JObjectExtensions
{
    public static IDictionary<string, object> ToDictionary(this JObject @object)
    {
        var result = @object.ToObject<Dictionary<string, object>>();

        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.

谢谢你们!

这篇关于转换成JObject&字典LT;字符串对象&gt ;.是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆