从对象字典C#中获取价值

时间:2013-11-07 12:24:51

标签: c# json object dictionary converter

我正在使用LiveConnect sdk获取一些用户信息 在做了必要的事情之后,这就是我得到的结果:

{
   "id": "123456789", 
   "name": "a b", 
   "first_name": "a", 
   "last_name": "b", 
   "link": "https://profile.live.com/", 
   "work": [], 
   "gender": null, 
   "emails": {
      "preferred": "a@live.com", 
      "account": "a@live.com", 
      "personal": null, 
      "business": null
   }, 
   "addresses": {
      "personal": {
         "street": null, 
         "street_2": null, 
         "city": null, 
         "state": null, 
         "postal_code": null, 
         "region": null
      }, 
      "business": {
         "street": null, 
         "street_2": null, 
         "city": null, 
         "state": null, 
         "postal_code": null, 
         "region": null
      }
   }, 
   "locale": "en_US", 
   "updated_time": "2013-10-10T08:41:14+0000"
}  

我需要在"account"内获取"emails" 首先,当我得到这个字符串时,我做了以下事情:

public Dictionary<string, object> userData = new Dictionary<string, object>();

userData = deserializeJsonObject(<the string above>);

private Dictionary<string, object> deserializeJsonObject(string json)
{
    var jss = new JavaScriptSerializer();
    var d = jss.Deserialize<Dictionary<string, object>>(json);
    return d;
}  

现在,为了获得帐户电子邮件,我打算做以下事情:

string email = userData["emails"]["account"];  

但由于这是一个字符串,对象字典,我得到一个错误,因为userData [“email”]是一个对象。

如何获取数据?

1 个答案:

答案 0 :(得分:1)

你试过演员吗?

例如:

(userData["emails"] as Dictionary<string,object>)["account"]

或:

((Dictionary<string,object>)userData["emails"])["account"]