我在C#中使用Graph API工作,並能夠獲取Facebook用戶個人資料信息,如ID,姓名和電子郵件,然後反序列化JSON以便能夠分配要標籤的值。Facebook Graph API檢索json和C#的朋友#
但是,我的問題是,當我去抓朋友列表或任何事情的列表,我該如何去反序列化C#中的這個JSON信息,以便我可以存儲數據?我相信我正在尋找一種將結果反序列化爲字典對象的方式,以便我可以循環訪問數據。
我在C#中使用Graph API工作,並能夠獲取Facebook用戶個人資料信息,如ID,姓名和電子郵件,然後反序列化JSON以便能夠分配要標籤的值。Facebook Graph API檢索json和C#的朋友#
但是,我的問題是,當我去抓朋友列表或任何事情的列表,我該如何去反序列化C#中的這個JSON信息,以便我可以存儲數據?我相信我正在尋找一種將結果反序列化爲字典對象的方式,以便我可以循環訪問數據。
呃..我結束了使用JSON.Net,它運作良好。謝謝你指出我的方向。在另一篇文章(http://www.mattcashatt.com)和JSON.net文件的幫助下,我能夠使所有的工作都能正常工作。以下是我使用的一些代碼。
#region JSON.Net User Profile
//Profile URL
url = "https://graph.facebook.com/me?fields=id,name,email&access_token=" + oAuth.Token;
JObject myProfile = JObject.Parse(requestFBData(url));
string myID = myProfile["id"].ToString().Replace("\"", "");
string myName = myProfile["name"].ToString().Replace("\"", "");
string email = myProfile["email"].ToString().Replace("\"", "");
lblID.Text = myID;
lblFullName.Text = myName;
lblEmail.Text = email;
imgUser.ImageUrl = "https://graph.facebook.com/me/picture?type=large&access_token=" + oAuth.Token;
#endregion
#region JSON.Net Friends
//Friends URL
url = "https://graph.facebook.com/me/friends?access_token=" + oAuth.Token;
JObject myFriends = JObject.Parse(requestFBData(url));
string id="";
string name = "";
//Loop through the returned friends
foreach (var i in myFriends["data"].Children())
{
id = i["id"].ToString().Replace("\"", "");
name = i["name"].ToString().Replace("\"", "");
lblFriends.Text = lblFriends.Text + "<br/> " + "id: " + id + " name: " + name + "<img src=" + "https://graph.facebook.com/" + id + "/picture>";
}
#endregion
}
}
}
public string requestFBData(string action)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(action);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
return results;
}
Thanks @zengr。我想我可以看看json.net – user402880 2010-07-27 11:25:28
你可以使用JSON解析器@zengr下面提到的,但真的 - DataContractJsonSerializer - 最JSON反序列化可以用內置的.NET deseriazlier來完成。您只需在要嘗試反序列化的類上使用正確的屬性(DataMember)。也許你可以粘貼JSON的樣子?也許看看這個SO問題:http://stackoverflow.com/questions/596271/deserialization-problem-with-datacontractjsonserializer – RPM1984 2010-07-27 06:39:25
我目前使用.NET的反序列化器的非列表類型字段,如用戶名和名稱。如果可能的話,我希望能夠堅持下去。 下面是我正在嘗試閱讀的朋友列表的一個示例。 {「data」:[{「id」:「123456」,「name」:「barney debble」},{「id」 「987654」,「name」:「wilma flintstone」},{「id」:「123654」,「name」:「fred flintstone」}]} – user402880 2010-07-27 11:24:44