问题描述
我在 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) &在运行时迭代属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)