Deserialize tweets returned from twitter api 1.1 c#

不打扰是莪最后的温柔 提交于 2019-12-24 15:09:57

问题


The following is returned to me when I pass in a particular screen name.

I've been following this Deserialize JSON into C# dynamic

I'm trying to reference the text field by doing the following:

       var serializer = new JavaScriptSerializer();

       dynamic data = serializer.Deserialize(tweets, typeof(object));

       for (int i = 0; i < data.Count; i++)
       {
           var t = data[i][3].text;    
       }

Clearly its wrong because I'm getting

Additional information: Operator '<' cannot be applied to operands of type 'int' and 'object[]'

Can some one help me retrieve the text for the tweet.


回答1:


As you an see, the text is an attribute of the root element of the json you are receiving.

I would recommend you using the Json.net library for parsing the json string and mapping it to objects you can use in your code. You can download it here: https://www.nuget.org/packages/newtonsoft.json/

In order to get the text from the json string you have to do the following:

  1. Create a class in c# with the desired attributes. This is the class, the root node's attributes will be mapped to. Do do this, you have to implement the attributes you want to process in your programm ( eg. "text").

    class Tweet{
    public string created_at { get; set; }
    public long id { get; set; }
    public string id_str { get; set; }
    public string text { get; set; }
    public string source { get; set; }
    }
    
  2. Now you can use the library to parse the Tweet object and after that get the text attribute.

    var tweet = JsonConvert.DeserializeObject<Tweet>(jsonString);
    var text = Tweet.text;
    


来源:https://stackoverflow.com/questions/29887709/deserialize-tweets-returned-from-twitter-api-1-1-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!