动态JContainer(JSON.NET)及遍历在运行时性能 [英] dynamic JContainer (JSON.NET) & Iterate over properties at runtime

查看:1620
本文介绍了动态JContainer(JSON.NET)及遍历在运行时性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了MVC4 / .NET4的WebAPI控制器操作的JSON字符串。该行动的参数是动态,因为我不知道有关我收到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自动分析所得动态对象是 Newtonsoft.Json.Linq.JContainer 。我能如市场预期,评估在运行时的属性,因此,如果JSON包含类似myobject.myproperty那么我现在可以把收到的动态对象,并在通话 myobject.myproperty C#code。到目前为止好。

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).

任何想法如何做到这一点?

Any idea how to do this?

推荐答案

我觉得这可能是一个起点。

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)及遍历在运行时性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆