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 :
1 |
{"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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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(); } } } |