Parsing JSON data in C# (JSON.NET, Linq, HttpClient)

Parsing JSON in C# is pretty simple. I’m a fan of using Newtonsoft.Json (known as JSON.NET) – I’ve found this to be the fastest, easiest JSON parser available.

Below are some steps to get parsing on your own (or jump down to the full source code). You can also grab this on GitHub. I’m just using a simple console app for this example. My JSON is also coming from a Google Custom Search (via http get). You’ll need to have your own JSON url (or maybe get a test url here).

  1. Start a new project > console application.
  2. In Package Manager Console, run: Install-Package Newtonsoft.Json
  3. Add the below to the top of your code file (Program.cs):
    using Newtonsoft.Json.Linq;
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
  4. Create a task to get some JSON data from http:public static async Task<string> httpResponse(string url)
    {
    IWebProxy iprox = WebProxy.GetDefaultProxy();
    iprox.Credentials = CredentialCache.DefaultCredentials;HttpClientHandler httpHandler = new HttpClientHandler()
    {
    UseProxy = true,
    Proxy = iprox,
    PreAuthenticate = true,
    UseDefaultCredentials = true,
    Credentials = CredentialCache.DefaultCredentials
    };using (var httpClient = new HttpClient(httpHandler))
    return await httpClient.GetStringAsync(url);
    }
  5. Now get some data:
    JObject jData = JObject.Parse(httpResponse(@”https://www.googleapis.com/customsearch/v1?youneedtocreateyourownlink&#8221;).Result);
  6. Read some simple data:
    string sampleValue = (string)jData[“url”][“type”];
  7. Read array of data:
    foreach (var sampleItem in jData[“items”])
    {
    string sampleItemValue = (string)sampleItem[“link”];
    Console.WriteLine(sampleItemValue);
    }

The full source:

using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace parsingJSON
{
    internal class Program
    {
        public static async Task<string> httpResponse(string url)
        {
            //i'm using a proxy, you could remove this if needed.
            IWebProxy iprox = WebProxy.GetDefaultProxy();
            iprox.Credentials = CredentialCache.DefaultCredentials;

            HttpClientHandler httpHandler = new HttpClientHandler()
            {
                UseProxy = true,
                Proxy = iprox,
                PreAuthenticate = true,
                UseDefaultCredentials = true,
                Credentials = CredentialCache.DefaultCredentials
            };

            using (var httpClient = new HttpClient(httpHandler))
                return await httpClient.GetStringAsync(url);
        }

        private static void Main(string[] args)
        {
            //get some JSON data
            JObject jData = JObject.Parse(httpResponse(@"https://yourJSONlinkhere").Result);

            string sampleValue = (string)jData["url"]["type"];

            Console.WriteLine(sampleValue);

            //loop through array in JSON
            foreach (var sampleItem in jData["items"])
            {
                string sampleItemValue = (string)sampleItem["link"];
                Console.WriteLine(sampleItemValue);
            }

            //filter w/ linq:

            var sampleArray =
              from p in jData["items"]
              select p;

            foreach (var sampleItem in sampleArray.Where(p => ((string)p["link"]).Contains("https")))
            {
                string sampleItemValue = (string)sampleItem["link"];
                Console.WriteLine(sampleItemValue);
            }

            Console.ReadLine();
        }
    }
}

View on GitHub

Parsing JSON data in C# (JSON.NET, Linq, HttpClient)

Leave a comment