c# - 解析来自 Twitter 的具有多个详细信息的 Json 数据

标签 c# json twitter json.net

我从 Twitter 获得以下输出,并且我只想从输出中捕获以下详细信息。

  1. 屏幕名称
  2. 关注者数量
  3. 个人资料图像网址

问题是数据位于嵌套的 Json 中。

Twitter API 输出:

[{ "contributors" : null,
"coordinates" : null,
"created_at" : "Wed Jan 29 09:18:15 +0000 2014",
"favorite_count" : 0,
"favorited" : false,
"geo" : null,
"id" : 428457050109382657,
"id_str" : "428457050109382657",
"in_reply_to_screen_name" : null,
"in_reply_to_status_id" : null,
"in_reply_to_status_id_str" : null,
"in_reply_to_user_id" : null,
"in_reply_to_user_id_str" : null,
"lang" : "en",
"place" : null,
"user" : { "contributors_enabled" : false,
    "follow_request_sent" : null,
    "followers_count" : 218,
    "id" : 609465835,
    "id_str" : "609465835",
    "is_translation_enabled" : false,
    "is_translator" : false,
    "lang" : "en",
    "listed_count" : 3,
    "location" : "Still alpha as hell.",
    "verified" : false
  }
}, 
{ "contributors" : null,
"coordinates" : null,
"created_at" : "Wed Jan 29 09:18:15 +0000 2014",
"favorite_count" : 0,
"favorited" : false,
"geo" : null,
"id" : 428457050109382657,
"id_str" : "428457050109382657",
"in_reply_to_screen_name" : null,
"in_reply_to_status_id" : null,
"in_reply_to_status_id_str" : null,
"in_reply_to_user_id" : null,
"in_reply_to_user_id_str" : null,
"lang" : "en",
"place" : null,
"user" : { "contributors_enabled" : false,
    "follow_request_sent" : null,
    "followers_count" : 1218,
    "id" :33333,
    "id_str" : "609465835",
    "is_translation_enabled" : false,
    "is_translator" : false,
    "lang" : "en",
    "listed_count" : 3,
    "location" : "N",
    "verified" : false
  }
}]

输出是

Json Output

我正在尝试使用 Newtonsoft Json 反序列化,但失败了。

代码如下:

        dynamic dynObj = JsonConvert.DeserializeObject(twitAuthResponse);
        foreach (var data in dynObj.user.data)
        {
            //Console.WriteLine("{0}", data.name);
            foreach (var fql in data.user)
            {
                foreach (JProperty keyValue in fql)
                {
                    Console.WriteLine("\t{0} : {1}", keyValue.Name, keyValue.Value);
                }
            }
        }

上面的代码返回错误“'Newtonsoft.Json.Linq.JArray'不包含'user'的定义”。

有人可以帮我吗?提前致谢!

最佳答案

请查看以下文章:http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx

您需要指定要反序列化的对象的类型,而不是使用动态类型。

类似于:var twitterJson = JsonConvert.DeserializeObject<TwitterResponse>(twitAuthResponse);

只要这个 .NET 对象与 JSON 的架构匹配,它就会自动映射,并且您可以访问所有强类型的属性和值。

关于c# - 解析来自 Twitter 的具有多个详细信息的 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431330/

相关文章:

asp.net-mvc - 从 ASP.NET MVC 中的 Json() 强制小写属性名称

c# - 如果另一个窗体正在其 MDI 父窗体中运行,如何从子窗体检查?

c# - 不像在 LINQ to SQL 中

c# - 如何创建序列号生成器?

javascript - iCanHaz.js + Mustache 不呈现数据对象中的第一行

javascript - 如何获取登录用户的 Twitter oAuth token

c# - 如何将文本字符串数组的数量限制为 15

java - 使用 HttpClient 将 URL 中的 JSON 查询字符串发送到 Web 服务 (Java)

php - 提交表单时用 # 和 @replies 标记单词!推特风格?

ios - 使用 Parse 框架发布推文