JsonObject to Model Facebook SDK

不想你离开。 提交于 2019-12-03 03:11:49

Maybe this code would help:

public class Friend
{
    public string Id { get; set; }
    public string Name { get; set; }
}

...

public ActionResult About()
{
    var app = new FacebookApp();
    var result = (JsonObject)app.Get("me/friends"));
    var model = new List<Friend>();

    foreach( var friend in (JsonArray)result["data"])
        model.Add( new Friend()
        {
            Id = (string)(((JsonObject)friend)["id"]),
            Name = (string)(((JsonObject)friend)["name"])
        };

    return View(model);
}

Now your model will be of type List<Friend>

You can also directly map from received data (JSON) to a list of objects using Json.NET. Something like this:

var fbData = app.Get("me/friends"));
var friendsList = JsonConvert.DeserializeObject<List<Friend>>(fbData.ToString());

It is very short and creates and populates the list automatically.

Note: mapping is done in a case-insensitive manner (class property can have different case than JSON property).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!