Wednesday, July 28, 2010

JSON Serialization and Deserialization for silverlight application while communicate with server using WCF - MVVM

Why JSON?

Because silverlight application communicate with WCF via asynchronous calls the size of data transfer must be minimized for that we can use JSON string instead of passing objects.

Implementation

Assume we have a customer basic information entry form. When the user fill in the form and clicks the Save we have to send the information to the server and save to the database using WCF service.

For this we need to keep a Data Type Object Definition in both server and client side say Customer Class as below:

   1: public class Customer : INotifyPropertyChanged
   2:     {
   3:         private string _firstName;
   4:         private string _lastName;
   5:         private string _address;
   6:         private string _city;
   7:         private string _pin;
   8:         private string _phone;
   9:  
  10:         public string FirstName
  11:         {
  12:             get
  13:             {
  14:                 return _firstName;
  15:             }
  16:             set
  17:             {
  18:                 _firstName = value;
  19:                 NotifyPropertyChanged("FirstName");
  20:             }
  21:         }
  22:         public string LastName
  23:         {
  24:             get
  25:             {
  26:                 return _lastName;
  27:             }
  28:             set
  29:             {
  30:                 _lastName = value;
  31:                 NotifyPropertyChanged("LastName");
  32:             }
  33:         }
  34:         public string Address
  35:         {
  36:             get
  37:             {
  38:                 return _address;
  39:             }
  40:             set
  41:             {
  42:                 _address = value;
  43:                 NotifyPropertyChanged("Address");
  44:             }
  45:         }
  46:         public string City
  47:         {
  48:             get
  49:             {
  50:                 return _city;
  51:             }
  52:             set
  53:             {
  54:                 _city = value;
  55:                 NotifyPropertyChanged("City");
  56:             }
  57:         }
  58:         public string Pin
  59:         {
  60:             get
  61:             {
  62:                 return _pin;
  63:             }
  64:             set
  65:             {
  66:                 _pin = value;
  67:                 NotifyPropertyChanged("Pin");
  68:             }
  69:         }
  70:         public string Phone
  71:         {
  72:             get
  73:             {
  74:                 return _phone;
  75:             }
  76:             set
  77:             {
  78:                 _phone = value;
  79:                 NotifyPropertyChanged("Phone");
  80:             }
  81:         }
  82:  
  83:         #region INotifyPropertyChanged Members
  84:  
  85:         public event PropertyChangedEventHandler PropertyChanged;
  86:         private void NotifyPropertyChanged(String propertyName)
  87:         {
  88:             if (PropertyChanged != null)
  89:             {
  90:                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  91:             }
  92:         }
  93:  
  94:         #endregion
  95:     }


We have to keep DTO objects in both client and sever side applications


Serialization


We have to write a template function which can serialize any object type. The JSON serialization is done through DataContractJsonSerializer class. To use DataContractJsonSerializer  you should include System.Runtime.Serialization.Json; and System.ServiceModel.Web libraries to your project. Following is the function which serialize the object to JSON string.



   1: public static string Serialize<T>(T data)
   2: {
   3:     using (var memoryStream = new MemoryStream())
   4:     {
   5:         var serializer = new DataContractJsonSerializer(typeof(T));
   6:         serializer.WriteObject(memoryStream, data);
   7:  
   8:         memoryStream.Seek(0, SeekOrigin.Begin);
   9:  
  10:         var reader = new StreamReader(memoryStream);
  11:         string content = reader.ReadToEnd();
  12:         return content;
  13:     }
  14: }


Deserialization


Following is the function for JSON Deserialization



   1: public static T Deserialize<T>(string jsonString)
   2: {
   3:     using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
   4:     {
   5:         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
   6:  
   7:         return (T)serializer.ReadObject(ms);
   8:     }
   9: }

How to serialize.


We have to define a static class with two static function for Serialization and deserialization.


Following is the serialization class:



   1: public static class Serializer
   2: {
   3:     public static T Deserialize<T>(string jsonString)
   4:     {
   5:         using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
   6:         {
   7:             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
   8:  
   9:             return (T)serializer.ReadObject(ms);
  10:         }
  11:     }
  12:  
  13:     public static string Serialize<T>(T data)
  14:     {
  15:         using (var memoryStream = new MemoryStream())
  16:         {
  17:             var serializer = new DataContractJsonSerializer(typeof(T));
  18:             serializer.WriteObject(memoryStream, data);
  19:  
  20:             memoryStream.Seek(0, SeekOrigin.Begin);
  21:  
  22:             var reader = new StreamReader(memoryStream);
  23:             string content = reader.ReadToEnd();
  24:             return content;
  25:         }
  26:     }
  27: }

You can serialize the Customer object like below:



   1: Serialize.Serializer.Serialize<Customer>(this.CustomerData);

Following is the code to deserialize JSON string to object. This you will do in the server to get the object back from JSON format:



   1: Serialize.Serializer.Deserialize<Customer>("JSONString");

The code for this article can be downloaded from here

3 comments:

DIE-HEART said...

memoryStream.Seek(0, SeekOrigin.Begin);

will you please tell me what is the use of Seek or what is the functionality of that and can we use JSON Serialization in MVVM model only.

Thanks dude,
Vishal

Catherine Higgins said...

Thanks for the awesome share
Hi we at Colan Infotech Private Limited , a company which is Situated in US and India, will provide you best service and our talented team will assure you best result and we are familiar with international markets, We work with customers in a wide variety of sectors. Our talented team can handle all the aspects of custom application development, we are the best among the dot net development companies in Chennai . asp .net web development company

We have quite an extensive experience working with
asp .net development services. we are the only
asp.net web development company which offer custom services to a wide range of industries by exceeding our client’s expectations. You can even interact directly with the team regarding your project, just as you would with your in-house team. hire asp.net programmers to achieve your dream product.

Custom application development company, asp.net development companies, asp .net web development company,Hire asp .net programmers,asp.net web development services,dot net development companies in chennai

Unknown said...


Thanks for your informative blog!!! Your article helped me to understand the installation process of .net programming language. Keep on updating your with such awesome information. best DOT NET Training in Chennai | .net course in Chennai

Post a Comment