如何使用C#序列化JsonArray?

时间:2017-01-07 07:36:20

标签: c# arrays json

所以我有一个Json数组如下:

{[data, [{"name":"Micheal Jackson","pic_large":"https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"}

如何使用C#对其进行序列化以将其解析为对象,然后将其传递给视图。

修改

{[data, [{"name":"Sayed Zubair Hashimi","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"},{"name":"Junaid Walizada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14055012_1760562554217155_4937121194048198140_n.jpg?oh=376b49c9d04c2676ebe3d853b122165e&oe=58EA033D","id":"1821833754756701"},{"name":"Mohib Akhondzada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/14264218_592094647641140_6351146344336469735_n.jpg?oh=a8a63893d71f76c45fa3d07389f1700a&oe=59147C84","id":"648198542030750"},{"name":"Za Beah","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15741112_359701871054520_6692094260041596196_n.jpg?oh=6d9a0e73f70145b821c79cbe738090a0&oe=58E5B5B5","id":"360411140983593"},{"name":"Baser Nader","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15094436_10153876544626432_1550234361821853528_n.jpg?oh=e197fa712b3180a20612ecdacb01747c&oe=58E54DEC","id":"10153975726331432"},{"name":"Abasin Deniz","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15698075_440749809647293_7905213567074684088_n.jpg?oh=aeb22664f458d75fc00638ca6fa4ecfc&oe=591F7BB3","id":"444098429312431"}]]}

EDIT2: 以下是我在Json上方检索的方法。

var appsecret_proof = access_token.GenerateAppSecretProof();

                var fb = new FacebookClient(access_token);

               dynamic myFeed = await fb.GetTaskAsync(
                    ("me/feed?fields=likes{{name,pic_large}}")
                    .GraphAPICall(appsecret_proof));

2 个答案:

答案 0 :(得分:2)

您问题中显示的字符串都是无效的JSON。格式正确的JSON可能如下所示:

{
    "data": [{
        "name": "Micheal Jackson",
        "pic_large": "https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938",
        "id": "10154729171332597"
    }]
}

现在,如果你想将它映射到C#类,这很容易做到。只需定义模型以反映此结构:

public class Feed
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("pic_large")]
    public string PicLarge { get; set; }
}

public class Result
{
    [JsonProperty("data")]
    public IList<Feed> Feeds { get; set; }
}

然后剩下的就是使用JSON序列化程序(例如Json.NET)将JSON字符串反序列化为此对象结构:

string json = ... the json string shown above
var result = JsonConvert.DeserializeObject<Result>(json);
foreach (var feed in result.Feeds)
{
    Console.WriteLine(feed.Name);
}

答案 1 :(得分:0)

首先,您需要创建具有与json相同属性的类,然后使用以下代码:

show.html.erb