Skip to content

Instantly share code, notes, and snippets.

@acamino
Last active November 6, 2023 11:46
Show Gist options
  • Star 77 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save acamino/51ae7fa45708bc1e8bcda5657374aa48 to your computer and use it in GitHub Desktop.
Save acamino/51ae7fa45708bc1e8bcda5657374aa48 to your computer and use it in GitHub Desktop.
4 Ways to Parse a JSON API with C#
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
namespace HttpClientApproach
{
internal class Contributor
{
public string Login { get; set; }
public short Contributions { get; set; }
public override string ToString()
{
return $"{Login, 20}: {Contributions} contributions";
}
}
internal class Program
{
private static void Main()
{
List<Contributor> contributors;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add("User-Agent", "Anything");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("repos/twilio/twilio-csharp/contributors").Result;
response.EnsureSuccessStatusCode();
contributors = response.Content.ReadAsAsync<List<Contributor>>().Result;
}
contributors.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace HttpWebClientApproach
{
internal class Contributor
{
public string Login { get; set; }
public short Contributions { get; set; }
public override string ToString()
{
return $"{Login, 20}: {Contributions} contributions";
}
}
internal class Program
{
private static void Main()
{
var webRequest = WebRequest.Create("https://api.github.com/repos/twilio/twilio-csharp/contributors") as HttpWebRequest;
if (webRequest == null)
{
return;
}
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Nothing";
using (var s = webRequest.GetResponse().GetResponseStream())
{
using (var sr = new StreamReader(s))
{
var contributorsAsJson = sr.ReadToEnd();
var contributors = JsonConvert.DeserializeObject<List<Contributor>>(contributorsAsJson);
contributors.ForEach(Console.WriteLine);
}
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using RestSharp;
namespace RestSharpApproach
{
internal class Contributor
{
public string Login { get; set; }
public short Contributions { get; set; }
public override string ToString()
{
return $"{Login, 20}: {Contributions} contributions";
}
}
internal class Program
{
private static void Main()
{
var client = new RestClient("https://api.github.com");
var request = new RestRequest("repos/twilio/twilio-csharp/contributors", Method.GET);
// Add HTTP headers
request.AddHeader("User-Agent", "Nothing");
// Execute the request and automatically deserialize the result.
var contributors = client.Execute<List<Contributor>>(request);
contributors.Data.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace WebClientApproach
{
[DataContract]
internal class Contributor
{
[DataMember(Name = "login")]
public string Login { get; set; }
[DataMember(Name = "contributions")]
public short Contributions { get; set; }
public override string ToString()
{
return $"{Login, 20}: {Contributions} contributions";
}
}
internal class Program
{
private const string Url = "https://api.github.com/repos/twilio/twilio-csharp/contributors";
private static void Main()
{
GetContributors();
GetContributorsAsync();
Console.ReadLine();
}
public static void GetContributors()
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nothing");
var content = client.DownloadString(Url);
var serializer = new DataContractJsonSerializer(typeof(List<Contributor>));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var contributors = (List<Contributor>)serializer.ReadObject(ms);
contributors.ForEach(Console.WriteLine);
}
}
public static void GetContributorsAsync()
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nothing");
client.DownloadStringCompleted += (sender, e) =>
{
var serializer = new DataContractJsonSerializer(typeof(List<Contributor>));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
{
var contributors = (List<Contributor>)serializer.ReadObject(ms);
contributors.ForEach(Console.WriteLine);
}
};
client.DownloadStringAsync(new Uri(Url));
}
}
}
@andreharak
Copy link

Amazing summary!
It helps a lot to give such an overview of the main possibilities in order to deepen the understanding.
Thanks a lot!

@parthdomadiay23
Copy link

great

@Hossain-Ahmed
Copy link

thanks

@Vikas-jk
Copy link

Thanks great examples, if anyone stumbles upon this and want to read dynamic json data, check
How to read JSON data in C# (Dynamic and simple json)
Thanks

@demndevel
Copy link

THANKS

@mertdurukan
Copy link

Thans

@Ebolicious
Copy link

@ifremmst
Copy link

Thanks man I have tested them all and got good experience

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment