WinRT APIでJSONフォーマットをデシリアライズする方法

現在、Twitterのフォロー/フォロワー状況を分析するWindowsストアアプリを作っています。Twitter APIは現在V1.1に移行することを推奨されているので、さぁ使おうとしたら、XML形式でのデータダウンロードはなくなっているんですね。

JSONか…ってことで、このポストではネットなどからダウンロードしたJSONフォーマットのテキストをWinRT APIを使ってC#でデシリアライズする方法を紹介します。

実はとっても簡単、DataContractJsonSerializerクラスを使います。namespaceは、System.Runtime.Serialization.Jsonです。例えばTwitterのFollowerを取得するAPIを使うと、フォローしているユーザーのIDのリストと、2000項目以上のフォロワーがいる場合に、更に情報を取得するためのカーサー情報がJSON形式で受信されます。これを解析するには、

    [DataContract]
    public class TwitterRelationships
    {
        [DataMember]
        public List<string> ids;
        [DataMember]
        public int next_cursor;
        [DataMember]
        public string next_cursor_str;
        [DataMember]
        public int previous_cursor;
        [DataMember]
        public string previous_cursor_str;
    }

という、受信テキストデータに合わせたクラスを定義して、以下を実行します。streamは、例えば、HttpWebResponseのGetResponseStream()メソッドで取得したJSONデータを取り出すストリームです。

    var ser = new DataContractJsonSerializer(typeof(TwitterRelationships ));
    TwitterRelationships tr = (TwitterRelationships )ser.ReadObject(stream);

これでお仕舞。簡単ですね。ちなみにユーザー情報をIDから取得したJSONをデシリアライズするには、

    [DataContract]
    public class TwitterUserProfile
    {
        [DataMember]
        public string id;
        [DataMember]
        public string screen_name;
        [DataMember]
        public string profile_image_url_https;
        [DataMember]
        public int followers_count;
        [DataMember]
        public bool Protected;
        [DataMember]
        public string description;
        [DataMember]
        public int friends_count;
        [DataMember]
        public string name;
    }

というようなクラスを定義して、

    var ser = new DataContractJsonSerializer(typeof(TwitterUserProfile));
    TwitterUserProfile tr = (TwitterUserProfile)ser.ReadObject(stream);

で、デシリアライズできます。クラスの定義の時は、JSONで記述されている全ての項目をプロパティとして定義する必要はなく、必要な項目だけ定義すればそれでOKです。