Friday, February 14, 2014

Working with JSON in c# using using Newtonsoft.Json

JSON stands for "Java Script Object Notation".
JSON you need a lightweight, open, text-based platform independent data exchange format for transferring data back and forth between the client and server. Although XML works well for many application scenarios but it has an extra payload that is XML tags.So to overcome this drawback ,JSON was introduced.
 In this example i will be using a library to access a WCF Rest Service using Newtonsoft.json.dll.
Here is the simple code to access a JSON array Response in c#
Just include Newtonsoft.Json and Newtonsoft.Json.Linq namespaces

Code:


 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net;

using System.Web.Script.Serialization;

using System.Net.Json;

using System.IO;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using Jsonparse;

 namespace Jsonparse

 {

 class Program

 {

 static void Main(string[] args)

 {

 WebClient c = new WebClient();

var data=c.DownloadString("http://localhost:50766/Service1.svc/json/GetDispatchOrders");

//ordtrnh is my custom class declared in Jsonparse namespace

 List

myDeserializedObjList = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(List));

 foreach(ordtrnh o in myDeserializedObjList) 

 { 

 Console.WriteLine("Customer Id is {0}",o.custid); 

 Console.WriteLine("Order Date is {0}", o.orddate);

 Console.WriteLine("Customer Area is {0}", o.parea); 

Console.WriteLine("----------------------------------------------");

 } 

 Console.ReadLine(); 

 } 

 } 

}
Output:
You can download newtonsoft.json.dll from   Here

No comments :

Post a Comment