【问题标题】:Parsing JSON from tweets从推文中解析 JSON
【发布时间】:2013-01-19 06:58:15
【问题描述】:

我正在尝试使用 JObject 从 Twitter 解析 C# 中的 JSON 对象我似乎无法弄清楚我需要的结果的起点在哪里。例如:

我需要得到以下内容:

  • 头像网址
  • 推特名称
  • 留言

JSON 字符串如下所示:

{"completed_in":0.01,"max_id":297026363595042816,"max_id_str":"297026363595042816","page":1,"query":"UOL01","re​​fresh_url":"?since_id=297026363595042816&q=O1" ,"结果":[{"created_at":"2013 年 1 月 31 日星期四 16:59:38 +0000","from_user":"CarrieLouiseH","from_user_id":252240491,"from_user_id_str":"252240491","from_user_name ":"Carrie Haworth","geo":null,"id":297026363595042816,"id_str":"297026363595042816","iso_language_code":"nl","metadata":{"result_type":"recent"}," profile_image_url “:” http://a0.twimg.com/profile_images/1721499350/5680_216695890261_521090261_7945528_588811_n_normal.jpg”, “profile_image_url_https”: “https://si0.twimg.com/profile_images/1721499350/5680_216695890261_521090261_7945528_588811_n_normal.jpg”, “源” :"web","text":"Test #01","to_user":null,"to_user_id":0,"to_user_id_str": "0","to_user_name":null}],"results_per_page":15,"since_id":0,"since_id_str":"0"}

我的假设是,如果我从“结果”开始,那么我可以访问“from_user”等。这是我的代码(到目前为止):

void DownloadStringCompleted(object senders, DownloadStringCompletedEventArgs e)
    {
        try
        {
            List<TwitterItem> contentList = new List<TwitterItem>();

            JObject ja = JObject.Parse(e.Result);
            int count = 0;

            JToken jUser = ja["results"];

            var name2 = (string)jUser["from_user_name"];
        }catch(Exception e){
         MessageBox.Show("There was an error");
        }
    }

但这似乎只是捕获了异常。有人对我哪里出错有任何想法吗?

【问题讨论】:

  • 检查异常以获取更多信息,尤其是 e.Message...

标签: c# json api twitter json.net


【解决方案1】:

您拥有的 JSON 不正确 - 元素 results[0]["source"] 的 " 应该被转义:

...,"source":"<a href=\"http://twitter.com/\">web</a>","...

另外,ja["results"] 是一个数组。您不能使用字符串索引器来获取其元素。您首先需要获取所需索引上的元素,然后您可以访问其from_user_name 属性:

JObject ja = JObject.Parse(e.Result);
int count = 0;
JToken jUser = ja["results"][0];
var name2 = (string)jUser["from_user_name"];

【讨论】:

  • 谢谢:)!那么ja["results"][0] 会根据while 循环而改变[0] 吗?那么它会随着它的经过而增加吗?
  • ja["results"] 是一个数组。如果您想要第一个元素,请获取ja["results"][0]。如果您想要所有元素,请在ja["results"].Children() 上枚举,您将获得所有元素。
猜你喜欢
  • 2017-12-03
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 2020-09-02
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多