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.
Asked
Active
Viewed 2,016 times
-2
-
http://stackoverflow.com/questions/401756/parsing-json-using-json-net – Der Kommissar Apr 27 '15 at 13:13
-
Internet is full of tutorials. For example [first result](https://blog.udemy.com/c-sharp-json/) when searching _JSON.NET Tutorial_ in Google. – Aleksandr Ivanov Apr 27 '15 at 13:16
-
Ok so I managed to get the data into a String DownloadData, Now what's the best way to get "display_name" : " ". Here's the code: WebClient client = new WebClient(); String DownloadData = client.DownloadString("https://api.twitch.tv/kraken/channels/mepphotv/follows?direction=DESC&limit=1&offset=0"); – DavixDevelop Apr 27 '15 at 16:03
1 Answers
1
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();

dbc
- 104,963
- 20
- 228
- 340