Click here to Skip to main content
15,942,934 members
Articles / Programming Languages / C#

Consuming JSON data in .NET with WCF

Rate me:
Please Sign up or sign in to vote.
4.74/5 (12 votes)
3 Feb 2009CPOL2 min read 104.9K   2.4K   61   9
Code showing how to consume JSON data in your .NET applications using the new JSON data contract support in .NET 3.5 SP1.

Parsing Arbitrary JSON in .NET Code

One of the emerging popular formats for sharing content online is JSON, shorthand for JavaScript Object Notation. Intended to be slightly more efficient than XML, it's found a home in lots of AJAX powered web applications. Some companies actually require you talk to their APIs in terms of JSON too, so having the ability to parse and emit arbitrary JSON in a strongly typed way is a valuable tool to have. As of .NET 3.5 SP1, we are equipped with the DataContractJsonSerializer.

This tutorial will show you how to take an arbitrary piece of JSON and convert it into an object. Let's take a feed from the popular Flikr photo sharing site. Taking the latest public photos feed, you might get JSON such as:

    "title": "Uploads from everyone",
    "link": "",
    "description": "",
    "modified": "2009-02-04T07:24:51Z",
    "generator": "",
    "items": [
            "title": "Ohayo2009-224",
            "link": "",
            "media": {
            "date_taken": "2009-01-29T16:47:42-08:00",            
            "description": "Description of photo appears here",
            "published": "2009-02-04T07:24:51Z",
            "author": "Author of photos appears here",
            "author_id": "14420000@N00",
            "tags": "2009 ohayo"
        .. more items

Break the Data into Objects

The trick now is to try and map the data structure into a set of .NET objects, and map each property on our objects to a field from the feed using the DataMember attribute. The classes themselves will be annotated with the DataContract attribute. Let's look at how we might do this for an 'item' from the Flikr feed we're using:

public class FlikrItem : IExtensibleDataObject 
    public String Title { get; set; }

    [DataMember(Name = "link", IsRequired = true)]
    public String Link { get; set; }

    public FlikrMedia Media { get; set; }

    // WCF stores any items we did not map here
    public ExtensionDataObject ExtensionData { get; set; }

As you can see, we've connected the elements from the JSON object to our .NET properties by using DataMember attributes. We've also implemented the IExtensibleDataObject interface, and told WCF to ignore any elements we haven't mapped explicitly and place them into what is effectively a bucket. Note that the media property is mapped to an instance of FlikrMedia, another type we have to declare to store the actual media imagery. All in all, our object model will look somewhat like:


Reading the JSON

Next, we have to read the JSON data into our objects using the DataContractJsonSerializer. Before we do this though, we have to manually process the string to remove the callback wrapping around the real JSON data, since the jsonFlikrFeed() wrapping will otherwise cause parsing to fail. Next, we have to convert the string we've downloaded from the API into a buffer of bytes, place it into a memory stream, and then pass that through to the serializer.

static FlikrFeed ParseFeed(String inputContent)
    // Remove the jsonFlikrFeed() callback cladding.
    inputContent = inputContent.Trim();
    if (inputContent.StartsWith("jsonFlickrFeed("))
        inputContent = inputContent.Remove(0, "jsonFlickrFeed(".Length);
    if (inputContent.EndsWith(")"))
        inputContent = inputContent.Substring(0, inputContent.Length-1);

    // Create a serializer for our type
    DataContractJsonSerializer serializer = 
       new DataContractJsonSerializer(typeof(FlikrFeed));

    // Convert the text to a buffer of bytes
    using (MemoryStream stream = 
           new MemoryStream(Encoding.Unicode.GetBytes(inputContent)))
        // Convert the stream buffer to an object with our serializer.
        return serializer.ReadObject(stream) as FlikrFeed;

And, that is that! We've now got an instance of FlikrFeed we can browse the Items collection of, and also drill down to the media item preview image. You can apply these principles to any JSON feed you wish to interact with!



  • For more general information about JSON, there's a fairly good introduction to the basics of JSON at Google's GWT FAQ. This introduces the idea of wrapping JSON inside callback functions (as flikr has done in our example).
  • You need the .NET Framework 3.5 SP1 installed in order to run this code, and you can find the serializer in the System.ServiceModel.Web namespace.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) Insurance Industry
United Kingdom United Kingdom
Steve Gray is a Senior Developer at a British insurance company, working on a popular aggregator. When he's not writing ASP .NET, it's because there's SQL or WCF to write instead.

Comments and Discussions

QuestionUnhandled Exception Pin
Member 1010461511-Jun-13 21:01
Member 1010461511-Jun-13 21:01 
QuestionDataContract for specific use case Pin
STHBRDG20-May-13 7:04
STHBRDG20-May-13 7:04 
QuestionConvert Datatable to JSON in using C# Pin
etechpulse8-Jan-13 20:08
etechpulse8-Jan-13 20:08 
QuestionThank you but can someone help Pin
qualar9-Feb-12 0:44
qualar9-Feb-12 0:44 
GeneralThank you! I have version in VB Pin
kbdguy26-Feb-10 6:01
professionalkbdguy26-Feb-10 6:01 
GeneralRe: Thank you! I have version in VB Pin
Member 815384411-Aug-11 3:38
Member 815384411-Aug-11 3:38 
GeneralFlickr Pin
tobywf9-Feb-09 6:36
tobywf9-Feb-09 6:36 
GeneralRe: Flickr Pin
Steven James Gray10-Feb-09 5:47
Steven James Gray10-Feb-09 5:47 
It was something I realized after I'd written it. I could always re-submit the code later, but to be honest the code works as is. The important part from my perspective is that it conveys the method, rather than the specific example.
GeneralGood article Pin
emiaj5-Feb-09 4:08
emiaj5-Feb-09 4:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.