How to parse JSON from C#

Posted on 12/15/2009 @ 12:35 AM in #WCF by | Feedback | 8332 views

WCF is VERY VERY elegant!! If you’re unfamiliar with WCF, boy are you behind times! No really, I mean it! Stop whatever you’re doing and learn WCF. This is a technology that every .NET dev will be required to know. Please see What is WCF? for a basic introduction on WCF. Followed by writing a simple Hello World WCF service, a WCF Client, and hosting such a service!

Also, I had pioneered the work of properly making WCF work in SharePoint 2007. Well, the good news is SharePoint 2010 has wholly embraced WCF. I mean, in every single respect. SharePoint 2010 has WCF flowing through it’s veins!!! I mean, the service architecture, client object model, ADO.NET data services, REST API, heck every damn thing in SP2010 uses WCF. .. I told you .. shudda learnt it :-). Anyway, still not too late! And my book will cover it well enough too.

WCF is cool because it is very very versatile. It is very well architected. One of the things WCF comes with is very good support for very thin clients, i.e. JavaScript, JSON etc.

Well y’know, JSON is awesome for many reasons too. Why I like JSON?

  1. It’s lightweight, quick and easy to transfer
  2. It is damn easy to parse in JavaScript
  3. It serializes and deserializes without messing up your HTML or such text with escapable characters
  4. It works beautifully with jQuery

Now it is pretty damn easy to parse in JavaScript, but did you know that WCF has pretty good support for deserializing JSON as well? I mean, right in C#!

Assuming that your WCF service looked like this –>

  1: [ServiceContract]
  2: public interface IMyWCFContract
  3: {
  4:     [OperationContract]
  5:     [WebGet(UriTemplate = "OperationName?parameterID={parameterID}", ResponseFormat = WebMessageFormat.Json)]
  6:     BusinessObjectType SomeCoolOperation(int parameterID);
  7: }

 

You could deserialize it into a strongly typed .NET object as shown below:

 

  1: HttpWebRequest webRequest = WebRequest.Create(serviceUrl) as HttpWebRequest;
  2: HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
  3: Encoding enc = Encoding.GetEncoding(1252);
  4: StreamReader configStream = new StreamReader(webResponse.GetResponseStream(), enc);
  5: string configuration = configStream.ReadToEnd();
  6: JavaScriptSerializer jSerialize = new JavaScriptSerializer();
  7: BusinessObjectType businessObject = jSerialize.Deserialize<BusinessObjectType>(configuration);
 
The above code will give you a strongly typed instance of BusinessObjectType in the client code!
Keep being cool!

Sound off but keep it civil:

Older comments..


On 12/15/2009 10:53:39 PM Fred Morrison said ..
You might want to augment this article with an actual BusinessObject, stressing the need to decorate each of the properties you want JSON'ized with [DataMember] and [ScriptIgnore] on the ones you don't want JSON'ized, like a DataSet. I actually ran into that issue with some legacy code that used an entity that included a DataSet property named Metadata. I couldn't get it to JSON'ize until I put [ScriptIgnore] on that property (which lucky for me, wasn't missed on the other end, a piece of javascript).


On 12/16/2009 12:45:16 AM Sahil Malik said ..
Fred - Excellent feedback! Y'know I'm exactly that in a particular project right now!


On 3/25/2011 10:15:31 PM Joe Miles said ..
Good job! :) I was using WCF data services, using REST directly over HTTP request/response gives me the flexibility if the columns change on the list.


On 7/19/2011 7:04:41 AM Manasa said ..
How to retrieve the Data from the JSON Object by filtrating the data with different condition?Can you explain with an example?… in c# 4.0.Pls Reply ASAP

Thanks in advance...


On 7/25/2012 7:57:43 AM organizasyon güvenliği said ..
was looking for an article I could not find a kind of continuous and thank you very much


On 10/9/2012 3:45:55 PM Brent said ..
Your code worked well. Thank You!

A couple of notes:


I was testing from a console app and reading a json string stored in a db, so I needed to add a reference to: System.Web.Extensions to access the fully-qualified namespace:

System.Web.Script.Serialization.JavaScriptSerializer

I also didn't know what my .net class would look like from the json string, but i found a free online site that converts your json into c# classes:

http://json2csharp.com/ (thanks to Jonathan Keith for this gem!)

It correctly converted this json:


{"itemDescription":{"description":"This item gives the owner massive health benefits.","menuitems": [{"value":"+750", "description":"Health"},{"value":"+20", "description":"HP5"}],"secondaryDescription":""}}

into these c# classes:


public class Menuitem


{


public string value { get; set; }


public string description { get; set; }


}

public class ItemDescription


{


public string description { get; set; }


public List<Menuitem> menuitems { get; set; }


public string secondaryDescription { get; set; }


}

public class RootObject


{


public ItemDescription itemDescription { get; set; }


}

so that your last line of code became:


var businessObject = jSerialize.Deserialize<RootObject>(configuration);

Thanks!