JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式。在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍,ASP.NET如何序列化和反序列化的处理,在序列化和反序列化对日期时间、集合、字典的处理。
JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式。
JSON是“名值对”的集合。结构由大括号'{}’,中括号'[]’,逗号’,’,冒号’:’,双引号’“”’组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。
JSON具有以下的形式:
对象(Object)是一个无序的“名值对”集合,一个对象以”{”开始,”}”结束。每个“名”后跟着一个”:”,多个“名值对”由逗号分隔。如:
1 |
var user={"name":"张三","gender":"男","birthday":"1980-8-8"} |
数组(Array)是值的有序集合,一个数组以“[”开始,以“]”结束,值之间使用“,”分隔。如:
1 |
var userlist=[{"user":{"name":"张三","gender":"男","birthday":"1980-8-8"}},{"user":{"name":"李四","gender":"男","birthday":"1985-5-8"}}]; |
字符串(String)是由双引号包围的任意数量的Unicode字符的集合,使用反斜线转义。
可以使用DataContractJsonSerializer类将类型实例序列化为JSON字符串,并将JSON字符串反序列化为类型实例。DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用;.NET Framework 4在System.Runtime.Serialization中。
利用DataContractJsonSerializer序列化和反序列化的代码:
1 |
1: using System; |
1 |
2: using System.Collections.Generic; |
1 |
3: using System.Linq; |
1 |
4: using System.Web; |
1 |
5: using System.Runtime.Serialization.Json; |
1 |
6: using System.IO; |
1 |
7: using System.Text; |
1 |
8: |
1 |
9: /// <summary> |
1 |
10: /// JSON序列化和反序列化辅助类 |
1 |
11: /// </summary> |
1 |
12: public class JsonHelper |
1 |
13: { |
1 |
14: /// <summary> |
1 |
15: /// JSON序列化 |
1 |
16: /// </summary> |
1 |
17: public static string JsonSerializer<T>(T t) |
1 |
18: { |
1 |
19: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
20: MemoryStream ms = new MemoryStream(); |
1 |
21: ser.WriteObject(ms, t); |
1 |
22: string jsonString = Encoding.UTF8.GetString(ms.ToArray()); |
1 |
23: ms.Close(); |
1 |
24: return jsonString; |
1 |
25: } |
1 |
26: |
1 |
27: /// <summary> |
1 |
28: /// JSON反序列化 |
1 |
29: /// </summary> |
1 |
30: public static T JsonDeserialize<T>(string jsonString) |
1 |
31: { |
1 |
32: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
33: MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); |
1 |
34: T obj = (T)ser.ReadObject(ms); |
1 |
35: return obj; |
1 |
36: } |
1 |
37: } |
序列化Demo:
简单对象Person:
1 |
1: public class Person |
1 |
2: { |
1 |
3: public string Name { get; set; } |
1 |
4: public int Age { get; set; } |
1 |
5: } |
序列化为JSON字符串:
1 |
1: protected void Page_Load(object sender, EventArgs e) |
1 |
2: { |
1 |
3: Person p = new Person(); |
1 |
4: p.Name = "张三"; |
1 |
5: p.Age = 28; |
1 |
6: |
1 |
7: string jsonString = JsonHelper.JsonSerializer<Person>(p); |
1 |
8: Response.Write(jsonString); |
1 |
9: } |
输出结果:
1 |
{"Age":28,"Name":"张三"} |
反序列化Demo:
1 |
1: protected void Page_Load(object sender, EventArgs e) |
1 |
2: { |
1 |
3: string jsonString = "{\"Age\":28,\"Name\":\"张三\"}"; |
1 |
4: Person p = JsonHelper.JsonDeserialize<Person>(jsonString); |
1 |
5: } |
运行结果:
ASP.NET中的JSON序列化和反序列化还可以使用JavaScriptSerializer,在System.Web.Script.Serializatioin命名空间下,需引用System.Web.Extensions.dll.也可以使用JSON.NET.
JSON格式不直接支持日期和时间。DateTime值值显示为“/Date(700000+0500)/”形式的JSON字符串,其中第一个数字(在提供的示例中为 700000)是 GMT 时区中自 1970 年 1 月 1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括“+0500”的部分可选,它指示该时间属于Local类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc。
修改Person类,添加LastLoginTime:
1 |
1: public class Person |
1 |
2: { |
1 |
3: public string Name { get; set; } |
1 |
4: public int Age { get; set; } |
1 |
5: public DateTime LastLoginTime { get; set; } |
1 |
6: } |
1 |
1: Person p = new Person(); |
1 |
2: p.Name = "张三"; |
1 |
3: p.Age = 28; |
1 |
4: p.LastLoginTime = DateTime.Now; |
1 |
5: |
1 |
6: string jsonString = JsonHelper.JsonSerializer<Person>(p); |
序列化结果:
1 |
{"Age":28,"LastLoginTime":"\/Date(1294499956278+0800)\/","Name":"张三"} |
1 、在后台使用正则表达式对其替换处理。修改JsonHelper:
1 |
1: using System; |
1 |
2: using System.Collections.Generic; |
1 |
3: using System.Linq; |
1 |
4: using System.Web; |
1 |
5: using System.Runtime.Serialization.Json; |
1 |
6: using System.IO; |
1 |
7: using System.Text; |
1 |
8: using System.Text.RegularExpressions; |
1 |
9: |
1 |
10: /// <summary> |
1 |
11: /// JSON序列化和反序列化辅助类 |
1 |
12: /// </summary> |
1 |
13: public class JsonHelper |
1 |
14: { |
1 |
15: /// <summary> |
1 |
16: /// JSON序列化 |
1 |
17: /// </summary> |
1 |
18: public static string JsonSerializer<T>(T t) |
1 |
19: { |
1 |
20: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
21: MemoryStream ms = new MemoryStream(); |
1 |
22: ser.WriteObject(ms, t); |
1 |
23: string jsonString = Encoding.UTF8.GetString(ms.ToArray()); |
1 |
24: ms.Close(); |
1 |
25: //替换Json的Date字符串 |
1 |
26: string p = @"\\/Date\((\d+)\+\d+\)\\/"; |
1 |
27: MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); |
1 |
28: Regex reg = new Regex(p); |
1 |
29: jsonString = reg.Replace(jsonString, matchEvaluator); |
1 |
30: return jsonString; |
1 |
31: } |
1 |
32: |
1 |
33: /// <summary> |
1 |
34: /// JSON反序列化 |
1 |
35: /// </summary> |
1 |
36: public static T JsonDeserialize<T>(string jsonString) |
1 |
37: { |
1 |
38: //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 |
1 |
39: string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; |
1 |
40: MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); |
1 |
41: Regex reg = new Regex(p); |
1 |
42: jsonString = reg.Replace(jsonString, matchEvaluator); |
1 |
43: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
44: MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); |
1 |
45: T obj = (T)ser.ReadObject(ms); |
1 |
46: return obj; |
1 |
47: } |
1 |
48: |
1 |
49: /// <summary> |
1 |
50: /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 |
1 |
51: /// </summary> |
1 |
52: private static string ConvertJsonDateToDateString(Match m) |
1 |
53: { |
1 |
54: string result = string.Empty; |
1 |
55: DateTime dt = new DateTime(1970,1,1); |
1 |
56: dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); |
1 |
57: dt = dt.ToLocalTime(); |
1 |
58: result = dt.ToString("yyyy-MM-dd HH:mm:ss"); |
1 |
59: return result; |
1 |
60: } |
1 |
61: |
1 |
62: /// <summary> |
1 |
63: /// 将时间字符串转为Json时间 |
1 |
64: /// </summary> |
1 |
65: private static string ConvertDateStringToJsonDate(Match m) |
1 |
66: { |
1 |
67: string result = string.Empty; |
1 |
68: DateTime dt = DateTime.Parse(m.Groups[0].Value); |
1 |
69: dt = dt.ToUniversalTime(); |
1 |
70: TimeSpan ts = dt - DateTime.Parse("1970-01-01"); |
1 |
71: result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds); |
1 |
72: return result; |
1 |
73: } |
1 |
74: } |
序列化Demo:
1 |
1: Person p = new Person(); |
1 |
2: p.Name = "张三"; |
1 |
3: p.Age = 28; |
1 |
4: p.LastLoginTime = DateTime.Now; |
1 |
5: |
1 |
6: string jsonString = JsonHelper.JsonSerializer<Person>(p); |
运行结果:
1 |
{"Age":28,"LastLoginTime":"2011-01-09 01:00:56","Name":"张三"} |
反序列化Demo:
1 |
string json = "{\"Age\":28,\"LastLoginTime\":\"2011-01-09 00:30:00\",\"Name\":\"张三\"}"; |
1 |
p=JsonHelper.JsonDeserialize<Person>(json); |
运行结果:
在后台替换字符串适用范围比较窄,如果考虑到全球化的有多种语言还会更麻烦。
2、利用JavaScript处理
1 |
1: function ChangeDateFormat(jsondate) { |
1 |
2: jsondate = jsondate.replace("/Date(", "").replace(")/", ""); |
1 |
3: if (jsondate.indexOf("+") > 0) { |
1 |
4: jsondate = jsondate.substring(0, jsondate.indexOf("+")); |
1 |
5: } |
1 |
6: else if (jsondate.indexOf("-") > 0) { |
1 |
7: jsondate = jsondate.substring(0, jsondate.indexOf("-")); |
1 |
8: } |
1 |
9: |
1 |
10: var date = new Date(parseInt(jsondate, 10)); |
1 |
11: var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; |
1 |
12: var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); |
1 |
13: return date.getFullYear() + "-" + month + "-" + currentDate; |
1 |
14: } |
简单Demo :
1 |
ChangeDateFormat("\/Date(1294499956278+0800)\/"); |
结果:
1 |
2011-1-8 |
在JSON数据中,所有的集合、字典和数组都表示为数组。
List<T>序列化:
1 |
1: List<Person> list = new List<Person>() |
1 |
2: { |
1 |
3: new Person(){ Name="张三", Age=28}, |
1 |
4: new Person(){ Name="李四", Age=25} |
1 |
5: }; |
1 |
6: |
1 |
7: string jsonString = JsonHelper.JsonSerializer<List<Person>>(list); |
序列化结果:
1 |
"[{\"Age\":28,\"Name\":\"张三\"},{\"Age\":25,\"Name\":\"李四\"}]" |
字典不能直接用于JSON,Dictionary字典转化为JSON并不是跟原来的字典格式一致,而是形式以Dictionary的Key作为名称”Key“的值,以Dictionary的Value作为名称为”Value“的值 。如:
1 |
1: Dictionary<string, string> dic = new Dictionary<string, string>(); |
1 |
2: dic.Add("Name", "张三"); |
1 |
3: dic.Add("Age", "28"); |
1 |
4: |
1 |
5: string jsonString = JsonHelper.JsonSerializer < Dictionary<string, string>>(dic); |
序列化结果:
1 |
1: "[{\"Key\":\"Name\",\"Value\":\"张三\"},{\"Key\":\"Age\",\"Value\":\"28\"}]" |
JSON官网:http://www.json.org/json-zh.html
独立JSON序列化:http://msdn.microsoft.com/zh-cn/library/bb412170.aspx
如何对JSON序列化和反序列化:http://msdn.microsoft.com/zh-cn/library/bb412179.aspx
form:http://www.cnblogs.com/zhaozhan/archive/2011/01/09/1931340.html