在Json中使用字典

本文关键字:字典 Json | 更新日期: 2023-09-27 18:18:22

如何将好友列表(如下)从字典中取出或取出?

例子
{
  "data": [
    {
      "name": "John Smith", 
      "id": "111"
    }, 
    {
      "name": "Alice Smith", 
      "id": "222"
    }, 
    {
      "name": "Mary Smith", 
      "id": "333"
    }
  ], 
  "paging": {
    "next": "https://graph.facebook.com/me/friends?format=json&limit=5000&offset=5000&__after_id=100003243976011"
  }
}

在Json中使用字典

  1. 您必须添加System。web和System.Web.Extensions程序集引用
  2. 然后尝试使用以下代码

jsonData字符串 = @"{ " 数据 ": [ { " 名称":"约翰·史密斯 ", " id ": " 111 " },
{ " 名称":"爱丽丝·史密斯 ", " id ": " 222 " },
{ " 名称":"玛丽·史密斯 ", " id ": " 333 " } ],
"paging": {"next": "https://graph.facebook.com/me/friends?format=json&limit=5000&offset=5000&__after_id=100003243976011"}}";

            JavaScriptSerializer seri = new JavaScriptSerializer();
            var items = seri.Deserialize<Dictionary<string, object>>(jsonData);
        // As data in JSON is array get it deserialize as ArrayList of Dictionary<string,object>
            var dataArray =  items["data"] as ArrayList;    
        // Each item in array list contain key value pair of name and id
            foreach (Dictionary<string,object> item in dataArray)
                {
        //Read Item
                foreach (KeyValuePair<string, object> detailItem in item)
                    {
                    Console.WriteLine(detailItem.Key + " - " + detailItem.Value);
                    }
                Console.WriteLine("-------------------------------------------");
        // Read Item
                }