dynamic JContainer (JSON.NET) amp; Iterate over properties at runtime(动态 JContainer (JSON.NET) amp;在运行时迭代属性)
问题描述
我在 MVC4/.NET4 WebApi 控制器操作中收到一个 JSON 字符串.该操作的参数是 dynamic
,因为我对接收端收到的 JSON 对象一无所知.
I'm receiving a JSON string in a MVC4/.NET4 WebApi controller action. The action's parameter is dynamic
because I don't know anything on the receiving end about the JSON object I'm receiving.
public dynamic Post(dynamic myobject)
自动解析 JSON,生成的 dynamic
对象是 Newtonsoft.Json.Linq.JContainer
.正如预期的那样,我可以在运行时评估属性,因此如果 JSON 包含类似 myobject.myproperty 的内容,那么我现在可以获取接收到的动态对象并在 C# 代码中调用 myobject.myproperty
.到目前为止一切顺利.
The JSON is automatically parsed and the resulting dynamic
object is a Newtonsoft.Json.Linq.JContainer
. I can, as expected, evaluate properties at runtime, so if the JSON contained something like myobject.myproperty then I can now take the dynamic object received and call myobject.myproperty
within the C# code. So far so good.
现在我想遍历作为 JSON 的一部分提供的所有属性,包括嵌套属性.但是,如果我这样做 myobject.GetType().GetProperties()
它只返回 Newtonsoft.Json.Linq.JContainer
的属性,而不是我正在寻找的属性(是 JSON 的一部分).
Now I want to iterate over all properties that were supplied as part of the JSON, including nested properties. However, if I do myobject.GetType().GetProperties()
it only returns properties of Newtonsoft.Json.Linq.JContainer
instead of the properties I'm looking for (that were part of the JSON).
知道怎么做吗?
推荐答案
我认为这可以作为一个起点
I think this can be a starting point
dynamic dynObj = JsonConvert.DeserializeObject("{a:1,b:2}");
//JContainer is the base class
var jObj = (JObject)dynObj;
foreach (JToken token in jObj.Children())
{
if (token is JProperty)
{
var prop = token as JProperty;
Console.WriteLine("{0}={1}", prop.Name, prop.Value);
}
}
编辑
这也可以帮助你
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());
这篇关于动态 JContainer (JSON.NET) &在运行时迭代属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:动态 JContainer (JSON.NET) &在运行时迭代属性


- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01