小编典典

使用 C# 反序列化 JSON

all

我正在尝试将 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);

它不起作用,因为原始对象无效。我怎样才能反序列化这个?


阅读 125

收藏
2022-06-10

共1个答案

小编典典

您需要创建这样的结构:

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
2022-06-10