JSON:JavaScript 对象表示法(JavaScript Object Notation)。
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
实例:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="json_test.aspx.cs" Inherits="Web_SoftAceTest.json.json_test" %>Untitled Page
类似 XML
- JSON 是纯文本
- JSON 具有“自我描述性”(人类可读)
- JSON 具有层级结构(值中存在值)
- JSON 可通过 JavaScript 进行解析
- JSON 数据可使用 AJAX 进行传输
相比 XML 的不同之处
- 没有结束标签
- 更短
- 读写的速度更快
- 能够使用内建的 JavaScript eval() 方法进行解析
- 使用数组
- 不使用保留字
JSON 值可以是:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 数组(在方括号中)
- 对象(在花括号中)
- null
json序列化与反序列化
json的序列化需要用到DataContractJsonSerializer类,在命名空间System.Runtime.Serialization.Json;下。.NET Framework 3.5需要添加System.ServiceModel.Web引用;.NET Framework 4在System.Runtime.Serialization中。
jsonhelper类:
public class JsonHelper { ////// json序列号 /// ////// /// public static string JsonSerializa (T t) { DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); zer.WriteObject(ms, t); string jsonstring = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonstring; } /// /// json反序列化 /// ////// /// public static T JsonDeserializa (string strjson) { DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strjson)); T obj = (T)zer.ReadObject(ms); return obj; } }
person类:
public class Person { public string Name { get; set; } public int Age { get; set; } }
简单实现:
protected void Page_Load(object sender, EventArgs e) { Person p = new Person(); p.Name = "Ace"; p.Age = 22; string json = JsonHelper.JsonSerializa(p); Response.Write(json); }
json序列化处理日期类型的处理
JSON格式不直接支持日期和时间。DateTime值值显示为“/Date(700000+0500)/”形式的JSON字符串,其中第一个数字(在提供的示例中为 700000)是 GMT 时区中自 1970 年 1 月 1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括“+0500”的部分可选,它指示该时间属于Local类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc。
修改jsonhelper类需用到的名称空间:
using System.Runtime.Serialization.Json; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic;//List名称空间
jsonhelper类的修改:
public class JsonHelper { ////// json序列化 /// ////// /// public static string JsonSerializer (T t) { DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); zer.WriteObject(ms, t); string jsonstring = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator me = new MatchEvaluator(ConvertJsonDateToDateString); Regex rg = new Regex(p); jsonstring = rg.Replace(jsonstring, me); return jsonstring; } /// /// json反序列化 /// ////// /// public static T JsonDeserializer (string jsonstring) { string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; MatchEvaluator me = new MatchEvaluator(ConvertDateTimeToJsonDate); Regex rg = new Regex(p); jsonstring = rg.Replace(jsonstring, me); DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)); T obj = (T)zer.ReadObject(ms); return obj; } /// /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串 /// /// ///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; } /// /// 将时间字符串转化成json时间 /// /// ///private static string ConvertDateTimeToJsonDate(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; } }
person类的修改:
public class Person { public string Name { get; set; } public int Age { get; set; } public DateTime LastLoginTime { get; set; } }
实例调用及对集合、字典、数组的处理:
protected void Page_Load(object sender, EventArgs e) { Person ps = new Person(); ps.Age = 22; ps.Name = "Ace"; ps.LastLoginTime = DateTime.Now; string json = JsonHelper.JsonSerializer(ps); Response.Write(json); List lt = new List () { new Person(){Name="Ace",Age=22,LastLoginTime=DateTime.Now}, new Person(){Name="Getes",Age=55,LastLoginTime=DateTime.Now} }; string jsonstring = JsonHelper.JsonSerializer
>(lt); Response.Write(jsonstring); Dictionary dy = new Dictionary (); dy.Add("Name", "Ace"); dy.Add("Age","22"); string json1 = JsonHelper.JsonSerializer >(dy); Response.Write(json1); }
用javascript处理
// 在后台替换字符串适用范围比较窄,如果考虑到全球化的有多种语言还会更麻烦。 //2. 利用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; } //简单Demo : //ChangeDateFormat("\/Date(1294499956278+0800)\/");