Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

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 97.1K   30   11
Explains how to use JSON serialization and deserialization in WCF DataContracts.

Introduction

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.

JSON and XML

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
    {
        [DataContract]
        internal class Person
        {
            [DataMember]
            internal string name;
            [DataMember]
            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();
                p.name = "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: ");
                Console.WriteLine(sr.ReadToEnd());
                 
            }

    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: " + p2.name);
    Console.Write("age=");
    Console.WriteLine(p2.age);
  10. Build the application once again, and see the deserialized results:
  11. Output:

    Deserialized Person data:
    Name: Bala
    age=22

Conclusion

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.

License

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

 
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.