Click here to Skip to main content
Click here to Skip to main content

Tagged as

JSON Serialization and Deserialization in ASP.NET

, 24 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
This article focuses on JSON Serialization and Deserialization in ASP.NET.

JSON is one kind of data format which is designer for running JavaScript on websites. At present, JSON is widely used in web. This article focuses on JSON Serialization and Deserialization in ASP.NET, including the brief introduction of JSON, how to serialize and deserialize with ASP.NET and operation on date, assembly, dictionary.

1. JSON Brief Introduction

JSON (JavaScript Object Notation) is one lightweight data exchange format.

JSON is "name/value" assembly. Its structure is made up with {}, [], comma, colon and double quotation marks. And it includes the following data types: Object, Number, Boolean, String, Array, NULL.

JSON has three styles:

  1. Object: An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example:
    var user={"name":"Tom","gender":"Male","birthday":"1983-8-8"}
  2. Array: Value order set. An array begins with "[" and end with "]". And values are separated with comma. For example:
    var userlist=[{"user":{"name":"Tom","gender":"Male","birthday":"1983-8-8"}},
        {"user":{"name":"Lucy","gender":"Female","birthday":"1984-7-7"}}]
  3. String: Any quantity unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.

2. Serialize and Deserialize JSON Data

We can use DataContractJsonSerializer to serialize type instance to JSON string and deserialize JSON string to type instance. DataContractJsonSerializer is under System.Runtime.Serialization.Json namespace. It is included in System.ServiceModel.Web.dll in .NET Framework 3.5 and System.Runtime.Serialization in .NET Framework 4.0. We need to add it as reference.

Code for Using DataContractJsonSerialize Serialize and Deserialize

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Runtime.Serialization.Json;
 using System.IO;
 using System.Text;  
 /// <summary>
 /// JSON Serialization and Deserialization Assistant Class
 /// </summary>
 public class JsonHelper
 {
     /// <summary>
     /// JSON Serialization
     /// </summary>
     public static string JsonSerializer<T> (T t)
     {
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
         MemoryStream ms = new MemoryStream();
         ser.WriteObject(ms, t);
         string jsonString = Encoding.UTF8.GetString(ms.ToArray());
         ms.Close();
         return jsonString;
     }  
     /// <summary>
     /// JSON Deserialization
     /// </summary>
     public static T JsonDeserialize<T> (string jsonString)
     {
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
         T obj = (T)ser.ReadObject(ms);
         return obj;
     }
 }

Serialization Demo

Simple Object Person:

 public class Person
 {
     public string Name { get; set; }
     public int Age { get; set; }
 }

Serialize as JSON String:

 protected void Page_Load(object sender, EventArgs e)
 {
     Person p = new Person();
     p.Name = "Tom";
     p.Age = 28;
  
     string jsonString = JsonHelper.JsonSerializer<person>(p);
     Response.Write(jsonString);
 }

Result

{"Age":28,"Name":"Tom"}

Reserialization Demo

 protected void Page_Load(object sender, EventArgs e)
 {
     string jsonString = "{\"Age\":28,\"Name\":\"Tom\"}";
     Person p = JsonHelper.JsonDeserialize<person>(jsonString);
 } 

Result

Serialization.png

In ASP.NET, JSON serializaation and deserialization can use JavaScriptSerializer which is under System.Web.Script.Serialization namespace. We need to add System.Web.Extensions.dll as reference or use JSON.NET.

3. JSON Serialization and Deserialization on DateTime

JSON cannot support date and time directly. The value of DateTime is shown as "/Date(700000+0500)/". The first number (700000) stands for milliseconds from Jan. 1, 1970 according to base time (not saylight saving time) in GMT. The number can be negative to present time before Jan. 1, 1970. The part "+0500" is optional. It present the time is Local, in other words, it can be converted to local time zone when deserializing. If this part is not there, the time will be deserialized as UTC.

Modify Person and add LastLoginTime

 public class Person
 {
     public string Name { get; set; }
     public int Age { get; set; }
     public DateTime LastLoginTime { get; set; }
 }
 Person p = new Person();
 p.Name = "Tom";
 p.Age = 28;
 p.LastLoginTime = DateTime.Now;  
 string jsonString = JsonHelper.JsonSerializer<person>(p);

Result of Serialization

{"Age":28,"LastLoginTime":"\/Date(1319266795390+0800)\/","Name":"Tom"}

I. Replace it with regular expression on background and modify JsonHelper

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Runtime.Serialization.Json;
 using System.IO;
 using System.Text;
 using System.Text.RegularExpressions;  

 /// <summary>
 /// JSON Serialization and Deserialization Assistant Class
 /// </summary>
 public class JsonHelper
 {
     /// <summary>
     /// JSON Serialization
     /// </summary>
     public static string JsonSerializer(T t)
     {
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
         MemoryStream ms = new MemoryStream();
         ser.WriteObject(ms, t);
         string jsonString = Encoding.UTF8.GetString(ms.ToArray());
         ms.Close();
         //Replace Json Date String                                         
         string p = @"\\/Date\((\d+)\+\d+\)\\/";
         MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
          Regex reg = new Regex(p);
         jsonString = reg.Replace(jsonString, matchEvaluator);
         return jsonString;
     }
  
     /// <summary>
     /// JSON Deserialization
     /// </summary>
     public static T JsonDeserialize(string jsonString)
     {
         //Convert "yyyy-MM-dd HH:mm:ss" String as "\/Date(1319266795390+0800)\/"
         string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
         MatchEvaluator matchEvaluator = new MatchEvaluator(
             ConvertDateStringToJsonDate);
         Regex reg = new Regex(p);
         jsonString = reg.Replace(jsonString, matchEvaluator);
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
         T obj = (T)ser.ReadObject(ms);
         return obj;
     }
  
     /// <summary>
     /// Convert Serialization Time /Date(1319266795390+0800) as String
     /// </summary>
     private static string ConvertJsonDateToDateString(Match m)
     {
         string result = string.Empty;
         DateTime dt = new DateTime(1970,1,1);
         dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
         dt = dt.ToLocalTime();
         result = dt.ToString("yyyy-MM-dd HH:mm:ss");
         return result;
     }
 
     /// <summary>
     /// Convert Date String as Json Time
     /// </summary>
     private static string ConvertDateStringToJsonDate(Match m)
     {
         string result = string.Empty;
         DateTime dt = DateTime.Parse(m.Groups[0].Value);
         dt = dt.ToUniversalTime();
         TimeSpan ts = dt - DateTime.Parse("1970-01-01");
         result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);
         return result;
     }
 }

Serialization Demo

 Person p = new Person();
 p.Name = "Tom";
 p.Age = 28;
 p.LastLoginTime = DateTime.Now;
  
 string jsonString = JsonHelper.JsonSerializer<person>(p);

Result

{"Age":28,"LastLoginTime":"2011-10-22 14:55:00","Name":"Tom"}

Deserialization Demo

string json = "{\"Age\":28,\"LastLoginTime\":\"2011-10-22 14:55:00\",\"Name\":\"Tom\"}";
p=JsonHelper.JsonDeserialize<person>(json);

Result

Serialization_2.png

II. Use JavaScript

 function ChangeDateFormat(jsondate) {
     jsondate = jsondate.replace("/Date(", "").replace(")/", "");
     if (jsondate.indexOf("+") > 0) {
         jsondate = jsondate.substring(0, jsondate.indexOf("+"));
     }
     else if (jsondate.indexOf("-") > 0) {
         jsondate = jsondate.substring(0, jsondate.indexOf("-"));
     }
  
     var date = new Date(parseInt(jsondate, 10));
     var month = date.getMonth() + 1 < 10 ? 
		"0" + (date.getMonth() + 1) : date.getMonth() + 1;
     var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
     return date.getFullYear() + "-" + month + "-" + currentDate;
 }

Simple Demo

ChangeDateFormat("\/Date(1319266795390+0800)\/");

Result

2011-10-22 14:55:00 

4. JSON Serialization and Deserialization Assembly, Dictionary and Array Disposition

In JSON data, all the assemblies, dictionaries and arrays are presented as array.

List Serialization

 List<person> list = new List<person>()
 {
     new Person(){ Name="Tom", Age=28},
     new Person(){ Name="Lucy", Age=27}
 };
  
 string jsonString = JsonHelper.JsonSerializer<list<person>>(list);

Serialization Result

"[{\"Age\":28,\"Name\":\"Tom\"},{\"Age\":27,\"Name\":\"Lucy\"}]"<

Dictionary cannot be used in JSON directly. If we want to convert Dictionary to JSON, we should take Key of Dictionary as value of name "Key and Value of Dictionary as value of "Value". For example:

 Dictionary<string,> dic = new Dictionary<string,>();
 dic.Add("Name", "Tom");
 dic.Add("Age", "28");
  
 string jsonString = JsonHelper.JsonSerializer < Dictionary<string,>>(dic);

Serialization Result

"[{\"Key\":\"Name\",\"Value\":\"Tom\"},{\"Key\":\"Age\",\"Value\":\"28\"}]"

Reference

Recommendation (Tips about ASP.NET)

License

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

Share

About the Author

SummiG

New Zealand New Zealand
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinprofessional VICK23-Oct-14 21:10 
QuestionDeserialization PinmemberMember 91193041-Aug-14 5:07 
GeneralMy vote of 3 PinmemberBenz19908-Oct-13 0:47 
QuestionDeserialization of json Pinmemberjagadishanil12-Jun-13 21:14 
BugError in code Dictionary<string,> PinmemberSingaporeSaravanan5-Jun-13 17:40 
GeneralRe: Error in code Dictionary<string,> PinmemberSingaporeSaravanan5-Jun-13 18:32 
QuestionSerialized JSON DateTime Format PinmemberMichael John Episcope7-May-13 18:18 
AnswerRe: Serialized JSON DateTime Format PinmemberEFEaglehouse8-Aug-13 11:33 
GeneralMy vote of 5 PinmemberDream8Lee27-Apr-13 17:45 
Questionwhy sometimes there is "_type" field in result, when i serialization a object? Pinmemberzhihua.you2-Apr-13 18:50 
GeneralMy vote of 5 Pinmemberjoaoalbuquerque30-May-12 6:16 
QuestionIssue wih WCF de-serialization Pinmemberdeepakkishore10-May-12 21:43 
QuestionAbout De-serializing a hashmap on a WCF service Pinmemberdeepakkishore10-May-12 21:37 
GeneralMy vote of 3 PinmemberPatrick Harris10-Apr-12 14:58 
GeneralMy vote of 4 PinmemberMonjurul Habib3-Nov-11 10:13 
GeneralRe: My vote of 4 PinmemberSummiG11-Dec-11 17:48 
GeneralMy vote of 5 PinmemberSunasara Imdadhusen2-Nov-11 20:21 
GeneralRe: My vote of 5 PinmemberSummiG11-Dec-11 17:48 
Thanks very much
QuestionI just did an article on this, which may be of interest for comparison PinmvpSacha Barber25-Oct-11 1:15 
AnswerRe: I just did an article on this, which may be of interest for comparison PinmemberSummiG11-Dec-11 17:47 
SuggestionThe type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference? Pinmembernewbegin24-Oct-11 13:31 
GeneralRe: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference? PinmemberSummiG24-Oct-11 16:55 
GeneralRe: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference? PinmemberSunasara Imdadhusen2-Nov-11 20:19 
QuestionWhy use DataContractJsonSerializer? PinmemberMember 442169523-Oct-11 11:36 
AnswerRe: Why use DataContractJsonSerializer? PinmemberHaBiX23-Oct-11 21:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 24 Oct 2011
Article Copyright 2011 by SummiG
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid