LoginSignup
3
5

More than 5 years have passed since last update.

Facebook SDK for .NETの戻り値で型付けを利用する

Last updated at Posted at 2016-06-07

概要

Facebook SDK for .NETでは、GetTaskAsync()等でユーザーのプロフィール情報等を取得できるのですが、型を何も指定しないとdynamic型で返されます。dynamic型は便利ではあるのですが、Visual StudioなどのIDEでインテリセンスが使えません。
後々のユニットテストや開発効率のことも考えると戻り値に型を持たせた方が良いため、そのように実装する方法を紹介します。

実装が終わると、下図のようにインテリセンスが効くようになります。
IntelliSense.gif

実装方法

Facebook Graph APIで、自分自身のプロフィール(/me)を取ってくる際に型付けを利用してみます。

まずは戻り値を受け取るクラスを定義する

まずは戻り値を格納するクラスを定義します。
Facebook Graph APIのリファレンス を参考に、APIの戻り値にどのようなフィールドがあるかを確認し、それに応じたクラスを定義します。
自分自身のプロフィール(/me)の場合、Graph APIからはUserオブジェクトが返ってきますので、それに応じたフィールドを適宜定義します。

public class AboutMeResult
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string gender { get; set; }
    public string id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public UserPicture picture { get; set; }
    public List<WorkExperience> work { get; set; } = new List<WorkExperience>();
}

public class WorkExperience
{
    public string id { get; set; }
    public string description { get; set; }
    public Page employer { get; set; }
    public Page location { get; set; }
    public string start_date { get; set; }
    public string end_date { get; set; }
    public Page position { get; set; }
}

public class UserPicture
{
    public ProfilePicture data { get; set; }
}

public class ProfilePicture
{
    public int height { get; set; }
    public int width { get; set; }
    public bool is_silhouette { get; set; }
    public string url { get; set; }
}

public class Page
{
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string link { get; set; }
}

API呼び出し結果を定義したクラスに詰めて返す

あとは、FacebookClientでのGetTaskAsync()呼び出し時に上で定義したAboutMeResultクラスを渡してあげます。
そうすると、AboutMeResultクラスのインスタンスが返されます。

using Facebook;

var client = new FacebookClient(facebookAccessToken);
var myself = await client.GetTaskAsync<AboutMeResult>(
    "/me"
    , new { fields = "first_name,last_name,gender,id,name,email,work,picture.width(999)", locale = "ja_JP" }
    );

// myselfはAboutMeResultのインスタンス。myself.last_name みたいにアクセス出来るし、インテリセンスも効く

参考情報

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5