Click here to Skip to main content
13,549,015 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


60 bookmarked
Posted 3 Feb 2009
Licenced CPOL

Consuming JSON data in .NET with WCF

, 3 Feb 2009
Rate this:
Please Sign up or sign in to vote.
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)


About the Author

Steven James Gray
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.

You may also be interested in...


Comments and Discussions

QuestionThank you but can someone help Pin
qualar9-Feb-12 0:44
memberqualar9-Feb-12 0:44 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04-2016 | 2.8.180515.1 | Last Updated 4 Feb 2009
Article Copyright 2009 by Steven James Gray
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid