在嵌套的ExpandoObject

时间:2016-03-21 19:57:30

标签: c# json win-universal-app expandoobject

我有以下代码:

        string responJsonText = "{'A609C5DC-E86A-11E5-BD37-3EF25AFC4F71': {'username': 'testuser1','mydata1': 52,'mydata2': 1,'mydata3': '+1889','lastupdate': '2016-03-21 11:49:28'},'C5DD67C5-F34B-34DC-DB67-4F5376BD7813': {'username': 'testuser2','mydata1': 52.7,'mydata2': 1.5,'mydata3': '+2373','lastupdate': '2016-03-20 14:38:28'}}"; 
        //data usually retrieved from web service
        dynamic response = new ExpandoObject();
        response = Newtonsoft.Json.JsonConvert.DeserializeObject<ExpandoObject>(responJsonText);

        foreach (KeyValuePair<string, object> kvp in response)
        {
            Debug.WriteLine("{0} = {1}", kvp.Key, kvp.Value);
            foreach (KeyValuePair<string, object> kvp2 in kvp.Value as ExpandoObject) 
                Debug.WriteLine("{0} = {1}", kvp2.Key, kvp2.Value);
        }

如您所见,它遍历每个json对象,然后遍历内部对象。

然而,我想使用更简单的东西,如下所示,但无法理解它:

//Just an example
foreach (var item in response) 
{
   Debug.WriteLine(item.username);
}

这可能吗?

1 个答案:

答案 0 :(得分:0)

有很多方法可以在username中获得responJsonText。一个简单的方法是Querying JSON with LINQ,如下所示:

string responJsonText = "{'A609C5DC-E86A-11E5-BD37-3EF25AFC4F71': {'username': 'testuser1','mydata1': 52,'mydata2': 1,'mydata3': '+1889','lastupdate': '2016-03-21 11:49:28'},'C5DD67C5-F34B-34DC-DB67-4F5376BD7813': {'username': 'testuser2','mydata1': 52.7,'mydata2': 1.5,'mydata3': '+2373','lastupdate': '2016-03-20 14:38:28'}}";

JObject o = JObject.Parse(responJsonText);
var children = o.Children().Children()["username"].Values<string>();

foreach (var item in children)
{
    Debug.WriteLine(item);
}

或使用SelectToken with JSONPath之类的:

JObject o = JObject.Parse(responJsonText);
IEnumerable<JToken> names = o.SelectTokens("$..username");

foreach (var item in names)
{
    Debug.WriteLine(item);
}