我正在尝试将Facebook朋友的Graph API 调用反序列化为对象列表。JSON对象如下所示:
{"data":[{"id":"518523721","name":"ftyft"}, {"id":"527032438","name":"ftyftyf"}, {"id":"527572047","name":"ftgft"}, {"id":"531141884","name":"ftftft"}, {"id":"532652067","name"... List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
它不起作用,因为原始对象无效。我该如何反序列化?
您需要创建这样的结构:
public class Friends { public List<FacebookFriend> data {get; set;} } public class FacebookFriend { public string id {get; set;} public string name {get; set;} }
然后,您应该可以执行以下操作:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
我的班级名称只是一个例子。您应该使用专有名称。
添加样本测试:
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<Friends>(json); foreach(var item in facebookFriends.data) { Console.WriteLine("id: {0}, name: {1}", item.id, item.name); }
产生:
id: 518523721, name: ftyft id: 527032438, name: ftyftyf id: 527572047, name: ftgft id: 531141884, name: ftftft