我有一个 Web API 方法,它接受任意 json 有效负载到 JObject
属性中.因此,我不知道会发生什么,但我仍然需要将其转换为 .NET 类型.我想要一个 Dictionary<string,object>
以便我可以以任何我想要的方式处理它.
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<string,object>
so that I can deal with it any way I want to.
我进行了很多搜索,但找不到任何东西,最终开始了一种混乱的方法来进行这种转换,一个键一个键,一个值一个值.有什么简单的方法吗?
I have searched a lot, but couldn't find anything and ended up starting a messy method to do this conversion, key by key, value by value. Is there an 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 football", "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 对象的第一级属性,但嵌套对象不会被转换为 Dictionary().
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 转换为 Dictionary<string, object>.是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!