我在 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模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)