0

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

我需要得到以下信息:

  • 头像网址
  • 推特名称
  • 信息

JSON 字符串如下所示:

{"completed_in":0.01,"max_id":297026363595042816,"max_id_str":"297026363595042816","page":1,"query":"UOL01","re​​fresh_url":"?since_id=297026363595042816&q=O1","re​​sults ":[{"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","source":"<a href="http://twitter .com/">web</a>","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"}","text":"测试#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"}","text":"测试#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");
        }
    }

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

4

1 回答 1

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"];
于 2013-02-04T14:51:52.007 回答