問題描述
我在 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模板網!