[英]Convert Json object to iEnumerable
我正在使用适用于.NET的Facebook SDK来从页面获取Facebook帖子,以将其显示在应用程序上。 我有以下课程:
public class Posts
{
public string id { get; set; }
public string Name { get; set; }
public string Message { get; set; }
public Uri PictureUri { get; set; }
}
public class FacebookPostsData
{
private static ObservableCollection<Posts> posts = new ObservableCollection<Posts>();
public static ObservableCollection<Posts> Posts
{
get
{
return posts;
}
}
}
并通过以下代码获取帖子:
FacebookClient fb = new FacebookClient(App.AccessToken);
dynamic postsTaskResult = await fb.GetTaskAsync("/mypage?fields=posts");
var result = (IDictionary<string, object>)postsTaskResult;
var data = (IEnumerable<object>)result["posts"];
foreach (var item in data)
{
var post = (IDictionary<string, object>)item;
FacebookPostsData.Posts.Add(new Posts { Name = (string)post["name"], id = (string)post["id"], Message = (string)post["message"], PictureUri = new Uri(string.Format("{0}", (string)post["picture"])) });
}
Frame.Navigate(typeof(Pages.next));
但是,result [“ posts”]返回一个Json对象,并且出现以下错误。
无法将类型为“ Facebook.JsonObject”的对象转换为类型为“ System.Collections.Generic.IEnumerable`1 [MyProject.ViewModel.Posts]”。
关于如何转换对象的任何想法?
该对象是类似以下内容的Facebook帖子:
"id": "339150749455906",
"posts": {
"data": [
{
"id": "339150749455906_545370565500589",
"from": {
"category": "Food/beverages",
"name": "Pepsi",
"id": "339150749455906"
},
"story": "Pepsi updated their cover photo.",
"picture": "http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/942740_545370555500590_46289134_s.jpg",
"link": "http://www.facebook.com/photo.php?fbid=545370555500590&set=a.365573920146922.72816.339150749455906&type=1&relevant_count=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/339150749455906/posts/545370565500589"
},
{
"name": "Like",
"link": "http://www.facebook.com/339150749455906/posts/545370565500589"
}
],
"privacy": {
"value": ""
},
我做了这样的事情
FacebookClient fb = new FacebookClient(App.AccessToken);
dynamic postsTaskResult = await fb.GetTaskAsync("/mypage?fields=posts");
foreach (var post in postsTaskResult.posts.data)//checking for nulls here would be safer
{
//var post = item; //JsonObject will do fine. I have not changed it
var name = ((IDictionary<String, object>)post).ContainsKey("name") ? (string)post.name : ""; //ContainsKey check optional
//var name = (string)post.name; //this would do fine
FacebookPostsData.Posts.Add(
new Posts {
Name = name,
id = (string)post["id"],
Message = (string)post["message"],
PictureUri = new Uri(string.Format("{0}", (string)post["picture"])) });
}
检查出来,让我知道。
免责声明:病床未经测试的代码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.