In this example i will printing out the list of movies that we get in the form of Json and print them out.
Step1: Create a console project
Step2: Add newtonsoft nuget package
Step3: I will be using a open source api that i will call to pint the title of the movie along with the release year. In this example i will print the movies which have the keyword beast in the title. So here is the code.
Snippet
private static void requestForMovies() { var request = WebRequest.Create("https://moviesapi.com/m.php?t=beast&y=&type=movie&r=json"); string text; var response = (HttpWebResponse)request.GetResponse(); using (var sr = new StreamReader(response.GetResponseStream())) { text = sr.ReadToEnd(); } var list = new List<MovieInfo>(); list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MovieInfo>>(text); foreach (var item in list) { Console.WriteLine("Title: " + item.Title + " Release Year: " + item.Year); } } public class MovieInfo { public string Id { get; set; } public string Title { get; set; } public string Year { get; set; } public string Poster { get; set; } public string Type { get; set; } }
In the above code the variable text have the resulting json text. which looks like this
[ { “id”: “5628302”, “title”: “Beast (III)”, “year”: “2017”, “poster”: “N/A”, “type”: “movie” }, { “id”: “6414796”, “title”: “Beast (V)”, “year”: “2017”, “poster”: “N/A”, “type”: “movie” }, { “id”: “4261746”, “title”: “Beast (VIII)”, “year”: “2017”, “poster”: “N/A”, “type”: “movie” }, { “id”: “1365050”, “title”: “Beasts of No Nation”, “year”: “2015”, “poster”: “N/A”, “type”: “movie” }, { “id”: “1152398”, “title”: “Beastly”, “year”: “2011”, “poster”: “N/A”, “type”: “movie” } ]
To deserialize it I will cal the newtonsoft deserializer that will map the json values to my object MovieInfo and provide me with the converted list.