C# 动态 JContainer (JSON.NET) & 在运行时迭代属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13652983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:20:33  来源:igfitidea点击:

dynamic JContainer (JSON.NET) & Iterate over properties at runtime

c#dynamicreflectionjson.net

提问by Alex

I'm receiving a JSON string in a MVC4/.NET4 WebApi controller action. The action's parameter is dynamicbecause I don't know anything on the receiving end about the JSON object I'm receiving.

我在 MVC4/.NET4 WebApi 控制器操作中收到一个 JSON 字符串。动作的参数是dynamic因为我对接收端的 JSON 对象一无所知。

 public dynamic Post(dynamic myobject)        

The JSON is automatically parsed and the resulting dynamicobject 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.mypropertywithin the C# code. So far so good.

JSON 会自动解析,结果dynamic对象是Newtonsoft.Json.Linq.JContainer. 正如预期的那样,我可以在运行时评估属性,因此如果 JSON 包含类似 myobject.myproperty 的内容,那么我现在可以获取接收到的动态对象并myobject.myproperty在 C# 代码中调用。到现在为止还挺好。

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.JContainerinstead of the properties I'm looking for (that were part of the JSON).

现在我想遍历作为 JSON 一部分提供的所有属性,包括嵌套属性。但是,如果我这样做,myobject.GetType().GetProperties()它只会返回 的属性Newtonsoft.Json.Linq.JContainer而不是我正在寻找的属性(这是 JSON 的一部分)。

Any idea how to do this?

知道如何做到这一点吗?

采纳答案by L.B

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);
    }
}

EDIT

编辑

this also may help you

这也可以帮助你

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());