Quantcast
Channel: Abu Ashraf Masnun » .NET
Viewing all articles
Browse latest Browse all 9

Quick JSON Parsing with C#

$
0
0

It’s quite sad that Microsoft doesn’t ship a decent JSON parser with .NET, not even the latest .NET 4. If we look at the web, everyone uses JSON today. Without no out of the box support for JSON, I was having much troubles consuming different APIs Services. But just a few moments ago, I found the JSON.NET project on CodePlex. The library has cool Linq integration that makes JSON parsing easier.

For test purposes, I am outputting this JSON string on http://localhost/json.php :

{"name":"masnun","email":["masnun@gmail.com","masnun@leevio.com"],"websites":{"home page":"http:\/\/masnun.com","blog":"http:\/\/masnun.me"}}

After downloading the JSON.NET package, I added a reference to “Newtonsoft.Json.dll”. Then used the following code snippet (C#) to parse the data and print the values from a console app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace JSONTest
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient c = new WebClient();
            var data = c.DownloadString("http://localhost/json.php");
            //Console.WriteLine(data);
            JObject o = JObject.Parse(data);
            Console.WriteLine("Name: "+o["name"]);
            Console.WriteLine("Email Address[1]: " + o["email"][0]);
            Console.WriteLine("Email Address[2]: " + o["email"][1]);
            Console.WriteLine("Website [home page]: " + o["websites"]["home page"]);
            Console.WriteLine("Website [blog]: " + o["websites"]["blog"]);
            Console.ReadLine();

        }
    }
}


Viewing all articles
Browse latest Browse all 9

Trending Articles