Deserialize JSON with C#

前端 未结 10 1453
一生所求
一生所求 2020-11-21 05:57

I\'m trying to deserialize a Facebook friend\'s Graph API call into a list of objects. The JSON object looks like:

{\"data\":[{\"id\":\"518523721\",\"name\"         


        
10条回答
  •  隐瞒了意图╮
    2020-11-21 06:26

    You need to create a structure like this:

    public class Friends
    {
    
        public List data {get; set;}
    }
    
    public class FacebookFriend
    {
    
        public string id {get; set;}
        public string name {get; set;}
    }
    

    Then you should be able to do:

    Friends facebookFriends = new JavaScriptSerializer().Deserialize(result);
    

    The names of my classes are just an example. You should use proper names.

    Adding a sample test:

    string json =
        @"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
    
    Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json);
    
    foreach(var item in facebookFriends.data)
    {
        Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
    }
    

    Produces:

    id: 518523721, name: ftyft
    id: 527032438, name: ftyftyf
    id: 527572047, name: ftgft
    id: 531141884, name: ftftft
    

提交回复
热议问题