Search code examples
c#jsonvisual-studiojson.nettwitch

C# Get data from twitch api for latest follower using JSON


Im trying to make a application that get's the latest follower from "https://api.twitch.tv/kraken/channels/mepphotv/follows?direction=DESC&limit=1&offset=0" and save it to a .txt file. I know how would I save the string 'display_name' to a txt file but I don't know how to get that data (display_name). I installed the JSON.NET on Visual Studio and searched the web for a answer but with no luck. Can someone please help me.


Solution

  • Define the following classes, adapted from the results of posting your JSON to http://json2csharp.com/ by using a Dictionary<string, string> for the _links properties and a DateTime for dates:

    public class User
    {
        public long _id { get; set; }
        public string name { get; set; }
        public DateTime created_at { get; set; }
        public DateTime updated_at { get; set; }
        public Dictionary<string, string> _links { get; set; }
        public string display_name { get; set; }
        public object logo { get; set; }
        public object bio { get; set; }
        public string type { get; set; }
    }
    
    public class Follow
    {
        public DateTime created_at { get; set; }
        public Dictionary<string, string> _links { get; set; }
        public bool notifications { get; set; }
        public User user { get; set; }
    }
    
    public class RootObject
    {
        public RootObject()
        {
            this.follows = new List<Follow>();
        }
        public List<Follow> follows { get; set; }
        public int _total { get; set; }
        public Dictionary<string, string> _links { get; set; }
    }
    

    Then, to deserialize, do:

            var root = JsonConvert.DeserializeObject<RootObject>(DownloadData);
    

    To get the latest follower (sorting by created_at date) do:

            var latestFollow = root.follows.Aggregate((Follow)null, (f1, f2) => (f1 == null || f2 == null ? f1 ?? f2 : f2.created_at > f1.created_at ? f2 : f1));
            var latestName = latestFollow.user.display_name;
    

    To sort all followers in reverse by created_at date, do:

            var sortedFollowers = root.follows.OrderByDescending(f => f.created_at).ToList();