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:
- 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"}
- 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"}}]
- 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 JSONstring
to type instance. DataContractJsonSerializer
is under System.Runtime.Serialization.Json
namespace. It is included in System.ServiceModel.Web.dll in .NET Framework 3.5 andSystem.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
In ASP.NET, JSON serializaation and deserialization can use JavaScriptSerializer
which is underSystem.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
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 ofDictionary
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
- JSON: http://www.json.org/
- Stand-Alone JSON Serialization: http://msdn.microsoft.com/en-us/library/bb412170.aspx
- Serialize and Deserialize JSON Data: http://msdn.microsoft.com/en-us/library/bb412179.aspx