Click here to Skip to main content
15,662,998 members
Articles / Programming Languages / C#
Posted 7 Jun 2009


30 bookmarked

JSON serialization and de-serialization in WCF DataContracts

Rate me:
Please Sign up or sign in to vote.
3.00/5 (10 votes)
7 Jun 2009CPOL3 min read
Explains how to use JSON serialization and deserialization in WCF DataContracts.


With XML becoming a thing of past for inter process communication and data exchange on the Internet infrastructures, JSON is more increasingly getting popular for providing quicker and better packaging of data across the wires. To be specific, as the need for partial rendering of web pages increases with the dynamic exchange of data using AJAX-enabled Web Services, JSON has become a more compact and simpler means to communicate between client calls and server processes thus providing a rich user experience. Moreover, Windows Communication Foundation (WCF) processes JSON messages using an internal, hidden mapping between JSON data and the XML infoset for data exchange.

This article discusses the features of JSON and how to perform a simple serialization of JSON data manually by an example.

JavaScript Object Notation

JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and server components. JSON encodes data using a subset of the object literals of JavaScript.


In WCF services and AJAX enabled Web Services, JSON encoding has become a better alternative in place of XML for exchange of data and messages. In general, XML elements are mapped into JSON strings while serialization, but it would be interesting to know how other parts of XML get serialized.

How to serialize/de-serialize JSON data?

Currently, in the .NET Framework 3.5, JSON serialization and de-serialization is implemented in WCF and AJAX-enabled Web Services. Retaining the other forms of serialization techniques such as Binary, SOAP, and XML, JSON is newly included in the framework, and is handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints.

JSON serialization is about serializing .NET type objects into JSON-encoded data, and is widely used in situations when writing Asynchronous JavaScript and XML (AJAX)-style Web applications. AJAX support in Windows Communication Foundation (WCF) is optimized for use with ASP.NET AJAX through the ScriptManager control.

JSON de-serialization is about de-serializion of JSON data into instances of .NET Framework types and objects to work at the client ends.

In cases where you need to directly work with JSON data, the DataContractJsonSerializer class is used, and it acts as a serialization engine that converts JSON data into instances of .NET Framework types and back into JSON data. A .NET objects that needs to be serialized must have a DataContract attribute attached to it, and its members must be attached with a DataMember attribute.

The DataContractJsonSerializer class consists of a WriteObject method to serialize a specific object to JSON data, and writes the resultant data to a stream. The ReadObject method reads the document stream in JSON format, and returns the deserialized object. But, this class currently has a bigger limitation that multiple members (fields, methods etc.) of the DataContract class cannot be serialized.

Here is a sample application that shows how to serialize and deserialize JSON data. Note that the DataContractJsonSerializer class works independently with out requiring a WCF configuration of your application. This helps us in serializing and de-serializing data manually.

Sample application

  1. Create a console application in the name JSONConsole and add a new class file Person.cs.
  2. C#
    using System.Runtime.Serialization;
    namespace JSONConsole
        internal class Person
            internal string name;
            internal int age;
  3. Add a reference to the assemblies System.ServiceModel.Web and System.Runtime.Serialization to the project.
  4. In the program.cs code file, write the following in the Main method:
  5. C#
    using System.IO;
    using System.Runtime.Serialization.Json;
    namespace JSONConsole
        class Program
            static void Main(string[] args)
                Person p = new Person();
       = "Bala";
                p.age = 22;
                MemoryStream stream1 = new MemoryStream();
                DataContractJsonSerializer ser = 
                  new DataContractJsonSerializer(typeof(Person));
                ser.WriteObject(stream1, p);
                stream1.Position = 0;
                StreamReader sr = new StreamReader(stream1);
                Console.Write("JSON serialized Person object: ");

    Note that the namespace System.Runtime.Serialization.Json is found in the System.ServiceModel.Web due to the usage of the DataContractJsonSerializer class in WCF and AJAX related services.

  6. Build the application, and see the serialized results as below in the console window:
  7. JSON serialized Person object: {"age":22,"name":"Bala"}.
  8. Now, for de-serialization, add the following code in the main method:
  9. C#
    stream1.Position = 0;
    Person p2 = (Person)ser.ReadObject(stream1);
    Console.WriteLine("Deserialized Person data:");
    Console.WriteLine("Name: " +;
  10. Build the application once again, and see the deserialized results:
  11. Output:

    Deserialized Person data:
    Name: Bala


This article has dealt with the new encoding format JavaScript Object Notation (JSON) introduced in .NET Framework 3.5 that performs quicker and faster data exchanges between client applications and servers. It also tells how to perform serialization of a .NET object to JSON encoding and back in WCF services.


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

Written By
Founder BB Systems CIT-GPNP
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

Suggestion[My vote of 1] Article is not accurately describing anything of value Pin
Draekz25-May-15 20:51
Draekz25-May-15 20:51 
GeneralMy Vote Of 3 Pin
Alireza_13622-Jun-13 4:20
Alireza_13622-Jun-13 4:20 
QuestionIgnore Pinheads posting here, Balamurali Pin
Cleveland Mark Blakemore26-May-13 20:19
Cleveland Mark Blakemore26-May-13 20:19 
GeneralMy vote of 1 Pin
gandla29-Mar-12 19:50
gandla29-Mar-12 19:50 
QuestionSerializing JSON string to Match WCF Service Function Parameter Pin
kartikps_197915-Dec-11 10:24
kartikps_197915-Dec-11 10:24 
I am facing problem serializing an object in JSON to match parameter name of WCF function call. The problem is to map the parameter name, i.e. the incoming JSON string should have the starting value as the same name as the parameter being passed in the function e.g.

"{\"GetComplexDataResult\":{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}}"
This is my WCF Function which I call in my client and as you can see the parameter name is same as the one which is being returned "GetComplexDataResult"

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
String SaveData(CompositeType GetComplexDataResult);
The problem which occurs is when I try to serialize my object using either Microsoft

System.Web.Script.Serialization.JavaScriptSerializer or any other library (e.g. Json.NET)

it only returns me {\"BoolValue\":true,\"StringValue\":\"Hello World!\"} even if I pass an object of the same class "CompositeType" (This is the client side code) e.g.

CompositeType GetComplexDataResult= new CompositeType();
GetComplexDataResult.BoolValue = true;
GetComplexDataResult.StringValue = "Hello World";

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(patchVersion);
My question is how can I get this JSON string

"{\"GetComplexDataResult\":{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}}"
Instead of

{\"BoolValue\":true,\"StringValue\":\"Hello World!\"}
with by just passing my object to JSON parser. I can concatenate it manually after I generate my JSON string, but that would be too much time consuming work. Is there any parser which solves this problem
GeneralMy vote of 1 Pin
Pr@teek B@h!17-Oct-11 8:15
Pr@teek B@h!17-Oct-11 8:15 
GeneralVery good Pin
softty22-Oct-10 18:15
softty22-Oct-10 18:15 
GeneralMy vote of 1 Pin
ottofischer8-Jul-10 19:55
ottofischer8-Jul-10 19:55 
GeneralMy vote of 1 Pin
Jimmy Zhang21-Jan-10 12:26
Jimmy Zhang21-Jan-10 12:26 
GeneralRe: My vote of 1 Pin
Cleveland Mark Blakemore26-May-13 20:25
Cleveland Mark Blakemore26-May-13 20:25 
QuestionChange to vb version? Pin
arpizt14-Dec-09 15:41
arpizt14-Dec-09 15:41 

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.