Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

JSON Serialization and Deserialization in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.89/5 (41 votes)
24 Oct 2011CPOL3 min read 472.5K   136   32
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:
    JavaScript
    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:
    JavaScript
    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

Java
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:

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

Serialize as JSON String:

Java
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

Java
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

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

Result of Serialization

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

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

Java
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

Java
Person p = new Person();
p.Name = "Tom";
p.Age = 28;
p.LastLoginTime = DateTime.Now;

string jsonString = JsonHelper.JsonSerializer<person>(p);

Result

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

Deserialization Demo

Java
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

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

JavaScript
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

Java
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:

Java
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)


Written By
New Zealand New Zealand
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionReamend Pin
Gabriel Lim12-Jul-18 22:26
Gabriel Lim12-Jul-18 22:26 
BugDateTime problem for dates in 1969 or earlier Pin
reo639-Jan-18 4:08
reo639-Jan-18 4:08 
GeneralRe: DateTime problem for dates in 1969 or earlier Pin
reo639-Jan-18 9:25
reo639-Jan-18 9:25 
Questionhow to deserialize ISO DateFormat Pin
Ye Htut7-Nov-17 23:47
Ye Htut7-Nov-17 23:47 
QuestionMy vote of 5 Pin
sebamarciano19-Nov-15 1:46
sebamarciano19-Nov-15 1:46 
GeneralMy vote of 5 Pin
VICK23-Oct-14 20:10
professional VICK23-Oct-14 20:10 
QuestionDeserialization Pin
Member 91193041-Aug-14 4:07
Member 91193041-Aug-14 4:07 
GeneralMy vote of 3 Pin
Gishisoft7-Oct-13 23:47
Gishisoft7-Oct-13 23:47 
QuestionDeserialization of json Pin
jagadishanil12-Jun-13 20:14
jagadishanil12-Jun-13 20:14 
BugError in code Dictionary<string,> Pin
SingaporeSaravanan5-Jun-13 16:40
SingaporeSaravanan5-Jun-13 16:40 
GeneralRe: Error in code Dictionary<string,> Pin
SingaporeSaravanan5-Jun-13 17:32
SingaporeSaravanan5-Jun-13 17:32 
QuestionSerialized JSON DateTime Format Pin
Michael John Episcope7-May-13 17:18
Michael John Episcope7-May-13 17:18 
AnswerRe: Serialized JSON DateTime Format Pin
EFEaglehouse8-Aug-13 10:33
EFEaglehouse8-Aug-13 10:33 
GeneralMy vote of 5 Pin
Dream8Lee27-Apr-13 16:45
Dream8Lee27-Apr-13 16:45 
Questionwhy sometimes there is "_type" field in result, when i serialization a object? Pin
zhihua.you2-Apr-13 17:50
zhihua.you2-Apr-13 17:50 
GeneralMy vote of 5 Pin
joaoalbuquerque30-May-12 5:16
joaoalbuquerque30-May-12 5:16 
QuestionIssue wih WCF de-serialization Pin
deepakkishore10-May-12 20:43
deepakkishore10-May-12 20:43 
QuestionAbout De-serializing a hashmap on a WCF service Pin
deepakkishore10-May-12 20:37
deepakkishore10-May-12 20:37 
GeneralMy vote of 3 Pin
Patrick Harris10-Apr-12 13:58
Patrick Harris10-Apr-12 13:58 
GeneralMy vote of 4 Pin
Monjurul Habib3-Nov-11 9:13
professionalMonjurul Habib3-Nov-11 9:13 
GeneralRe: My vote of 4 Pin
SummiG11-Dec-11 16:48
SummiG11-Dec-11 16:48 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen2-Nov-11 19:21
professionalSunasara Imdadhusen2-Nov-11 19:21 
GeneralRe: My vote of 5 Pin
SummiG11-Dec-11 16:48
SummiG11-Dec-11 16:48 
QuestionI just did an article on this, which may be of interest for comparison Pin
Sacha Barber25-Oct-11 0:15
Sacha Barber25-Oct-11 0:15 
AnswerRe: I just did an article on this, which may be of interest for comparison Pin
SummiG11-Dec-11 16:47
SummiG11-Dec-11 16:47 

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.