使用C#解析Json Response对象

时间:2014-10-11 13:05:25

标签: c# json facebook-graph-api

我正在通过发布到garph api获取facebook newsfeed的故事标签,如下所示,并获取其内容如下的json响应对象

  {
 "from": {
  "category": "Recreation/sports website",
  "name": "Cricinfo",
  "id": "18429207554"
 },
"id": "18429207554_10152399273812555",
"created_time": "2014-10-11T04:48:21+0000"
}

现在我想在c#中解析这个对象以获取“name”字段值和“id”字段值...有人可以指导我如何解析json对象并获取值

 Newsfeed_Id = jsonObj1.Data([i]).id
                            Dim requestgetTags As WebRequest = _
          WebRequest.Create("https://graph.facebook.com/v2.1/" & Newsfeed_Id & "?fields=from,story_tags&access_token=" & _Obj.AccessToken & "")

                            requestgetTags.Credentials = CredentialCache.DefaultCredentials
                            Dim responsegetTags As WebResponse = requestgetTags.GetResponse()
                            Console.WriteLine(CType(responsegetTags, HttpWebResponse).StatusDescription)
                            Dim dataStreamgetTags As Stream = responsegetTags.GetResponseStream()
                            Dim readergetTags As New StreamReader(dataStreamgetTags)
                            Dim responseFromServergetTags As String = readergetTags.ReadToEnd()

1 个答案:

答案 0 :(得分:0)

首先,您的代码示例是在VB上,而不是C#。 但是如果你仍然想在C#中解析json,这里有一个如何做到这一点的例子。

var parsedResponse = JsonConvert.DeserializeObject<NewsFeed>(jsonResponse);

要使其工作,您应该使用Newtonsoft.Json dll并指定NewsFeed类,如下所示:

    public class NewsFeed
    {
      public string Id;
      public string CreatedTime;
      public Tag From;
    }

    public class Tag
    {
      [JsonConstructor]
      public NewsFeed(string category, string name, string id)
      {
         Category = category;
         Name = name;
         Id = id
      }
      public string Category;
      public string Name;
      public string Id;
    }