JsonObject to Model Facebook SDK
Asked Answered
J

2

8

I'm have to use the facebook c# sdk for a new poject in .net 3.5 , I'm aware that the latest version has examples for 4 - but it's also compiled against the 3.5 so works completely.

Anyway, and forgive me if I'm being incredibly dumb. But i'm looking to convert a json object into my model, can I do something like this?

public ActionResult About()
{
    var app = new FacebookApp();
    JsonObject friends = (JsonObject)app.Get("me/friends");
    ViewData["Albums"] = new Friends((string)friends.ToString());
    return View();
}

public class Friends
{
    public string name { get; set; }
    public string id { get; set; }

    public Friends(string json)
    {
        JArray jObject = JArray.Parse(json);
        JToken jData = jObject["data"];

        name = (string)jData["name"];
        id = (string)jData["id"];
    }
}

This is using Json.Net. Obviously this doesn't work, the error I get back is

Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject

I'm pretty sure that I'm going completely the wrong way around this - so if anyone can offer any tips I'd be incredibbly grateful.

Jamila answered 20/1, 2011 at 14:56 Comment(0)
M
14

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>

Mauceri answered 20/1, 2011 at 23:30 Comment(0)
F
0

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).

Floccule answered 14/2, 2017 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.