如何从c#中的Dictionary <string,object>中检索对象值

时间:2017-03-26 16:47:55

标签: c# json dictionary

我有字符串,对象格式的字典。

Dictionary<string, object> responseList = null;
    responseList = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(response["Content"]);

在上面的字典中,我有以下JSON数据。

> {   "_links": {
>     "account": {
>       "href": "https://api-uat.dwolla.com/accounts/ec297a2c-f681-417b-9668-8f3ebcd33060",
>       "type": "application/vnd.dwolla.v1.hal+json",
>       "resource-type": "account"
>     },
>     "events": {
>       "href": "https://api-uat.dwolla.com/events",
>       "type": "application/vnd.dwolla.v1.hal+json",
>       "resource-type": "event"
>     },
>     "webhook-subscriptions": {
>       "href": "https://api-uat.dwolla.com/webhook-subscriptions",
>       "type": "application/vnd.dwolla.v1.hal+json",
>       "resource-type": "webhook-subscription"
>     },
>     "customers": {
>       "href": "https://api-uat.dwolla.com/customers",
>       "type": "application/vnd.dwolla.v1.hal+json",
>       "resource-type": "customer"
>     }   } }

我想检索帐户部分的href,即“https://api-uat.dwolla.com/accounts/ec297a2c-f681-417b-9668-8f3ebcd33060”。我已经通过

检索了字典的对象部分
  var result = responseList["_links"];

如何进一步处理此对象变量以检索“帐户”的href值?谢谢你的期待

2 个答案:

答案 0 :(得分:1)

您可以将foreach迭代用于嵌套的Json

foreach(var outer in responseList)
{
foreach (var middle in (Dictionary<string, object>) outer.Value)
{
     foreach (var inner in (Dictionary<string, string>) middle.Value)
     {
       Jsondata data = new Jsondata();
       data.href = inner["href"]; 
     }      
}
}

public class Jsondata
{
 public string href { get; set; }
 public string type { get; set; }
 public string resource{ get; set; }
}

此致

Thiyagu Rajendran

**如果有帮助,请将回复标记为答案。

答案 1 :(得分:1)

为什么不使用JObject来解析JSON?我拿了一个你的JSON样本,并能够将数据解析成一个对象并使用它如下所示:

        JObject j = JObject.Parse(jsonData);

        Console.WriteLine(j["_links"]["account"]["href"]);