New User?   Join Now     Login            Forgot Password?    
Browse by Category
Articles
Games
Algorithms
Software
Browse Projects
XamlQuery v1.2
YtoX
Racketbot
Browse Topics
Json Serialization Utility  (8126 hits)
 Share this Article
 
Posted by Prabu Arumugam on Jun-22-2010
Languages: C#, Silverlight

About JSON

JSON is the acronym for JavaScript Object Notation. It is a lightweight text-based data storage and interchange format. It is a subset of object literal notation in JavaScript language. Despite its relationship to JavaScript, it is considered to be a language-independent data format and widely hailed as the successor and lightweight alternative to XML format. For more information on JSON history and structure, visit http://en.wikipedia.org/wiki/JSON OR http://www.json.org/.

JSON is most widely used for exchange of information between the browser and server in a web application, typically for asynchronous calls using AJAX or ASP.NET callback. Another typical usage is to store complex data structures in databases. An entire object can be stored in a single field of the database table. Using JSON, we can build a more advanced non-relational data-store similar to Amazon SimpleDB. However, Amazon SimpleDB is much more advanced and different from this.

About DataContractJsonSerializer

In this article, we use DataContractJsonSerializer to serialize and deserialize any type of object. The main advantage of this class is that it is available in both .NET frameworks, normal version and Silverlight version, so that you can use the serialization techniques in a base class library (like business-entity layer) itself. You have to add reference to System.Runtime.Serialization and System.ServiceModel.Web namespaces in order to use DataContractJsonSerializer class, as shown in the following image.

JSON Serialization

The following function converts any object to its equivalent JSON string representation.

        public static string SerializeObject(object sourceObject)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(sourceObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, sourceObject);
                using (StreamReader reader = new StreamReader(stream))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    return (reader.ReadToEnd());
                }
            }
        }

JSON Deserialization

The following function converts the JSON string representation back to the original object. The type of the object has to be speicified through generic parameter in angle brackets.

        public static T DeserializeObject(string json)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return ((T)serializer.ReadObject(ms));
            }
        }

About JsonUtility and its Usage

JsonUtility class contains the above two static methods namely SerializeObject() and DeserializeObject() for serialization and deserialization, respectively. You can add this class to both normal class library and Silverlight class library. Once you add this class to your business-entities class library, you can create ToJson() method and FromJson() static method in all your business-entity classes. For example, consider the following Person class with these methods.

    public class Person
    {
        #region Properties
		
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
		
        #endregion
		
        #region Methods
		
        public string ToJson()
        {
            return (JsonUtility.SerializeObject(this));
        }
		
        #endregion
		
        #region Static-Methods
		
        public static Person FromJson(string json)
        {
            return (JsonUtility.DeserializeObject(json));
        }
		
        #endregion
    }

The following sample code illustrates the usage of ToJson() method. We create an instance of Person class and serialize it to JSON using ToJson() method.

    Person person = new Person() { FirstName = "Sam", LastName = "Anderson", Age = 24, Gender = "Male" };
    person.PhoneNumbers = new List() { "121212", "454545" };
    string json = person.ToJson();

The above sample code creates the JSON string like below.

{
	"FirstName" : "Sam",
	"LastName" : "Anderson",
	"Age" : 24,
	"Gender" : "Male",
	"PhoneNumbers" : ["121212", "454545"]
}

Instead of including ToJson() and FromJson() methods in each business-entity class, you can create an abstract base class like BusinessEntity and include the ToJson() and FromJson() methods in this abstract class. So, you can call these methods from all business-entity classes without replicating.


 Downloads for this article
File Language Tools
JsonUtility.cs  553 bytes  (29 downloads) C#

 Share this Article

 Comments on this Article
No comments on this article.
 Post your comment here
Your Name
Your Email
Comment
Post Comment

About About      Terms Terms      Contact Contact
codeding on Facebook Facebook      codeding on Twitter Twitter