一、JSON简介
JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式。
JSON是“名值对”的集合。结构由大括号'{}',中括号'[]',逗号',',冒号':',双引号'“”'组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。
JSON具有以下的形式:
对象(Object)是一个无序的“名值对”集合,一个对象以”{”开始,”}”结束。每个“名”后跟着一个”:”,多个“名值对”由逗号分隔。如:
{"FirstName":"Jason","LastName":"Chen"}
数组(Array)是值的有序集合,一个数组以“[”开始,以“]”结束,值之间使用“,”分隔。如:
[{"FirstName":"Jason","LastName":"Chen"},{"FirstName":"Jason","LastName":"Chen"}]
字符串(String)是由双引号包围的任意数量的Unicode字符的集合,使用反斜线转义。
二、对数据进行序列化
可以使用JavaScriptSerializer类将类型实例序列化为JSON字符串。
利用JavaScriptSerializer序列化的代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
/*
* JavaScriptSerializer在System.Web.Script.Serialization命名空间下。
* create by cjj on 2014-10-08;email:ijasonchen91@sina.com
*/
namespace mob
{
/// <summary>
/// JSON序列化和反序列化辅助类
/// </summary>
public static class JsonHelper
{
/// <summary>
/// JSON序列化
/// </summary>
/// <param name="obj">源对象</param>
/// <returns>json数据格式</returns>
public static string ToJson(object obj)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
return serialize.Serialize(obj);
}
/// <summary>
/// 将字符串数组转换为json数据格式:["value1","value2",...]
/// </summary>
/// <param name="strs">字符串数组</param>
/// <returns>json数据格式</returns>
public static string ToJson(this string[] strs)
{
return ToJson((object)strs);
}
/// <summary>
/// 将DataTable数据源转换为json数据格式:[{"ColumnName":"ColumnValue",...},{"ColumnName":"ColumnValue",...},...]
/// </summary>
/// <param name="dt">DataTable数据源</param>
/// <returns>json数据格式</returns>
public static string ToJson(this DataTable dt)
{
List<object> list = new List<object>();
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc].ToString());
}
list.Add(dic);
}
return ToJson(list);
}
/// <summary>
/// 将"\/Date(673286400000)\/"Json时间格式替换"yyyy-MM-dd HH:mm:ss"格式的字符串
/// </summary>
/// <param name="jsonDateTimeString">"\/Date(673286400000)\/"Json时间格式</param>
/// <returns></returns>
public static string ConvertToDateTimeString(this string jsonDateTimeString)
{
string result = string.Empty;
string p = @"\\/Date\((\d+)\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
result = reg.Replace(jsonDateTimeString, matchEvaluator);
return result;
}
public static string ConvertJsonDateToDateString(Match match)
{
string result = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
}
}
简单对象Person:
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname, DateTime birthday)
{
this.FirstName = firstname;
this.LastName = lastname;
this.Birthday = birthday;
}
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public DateTime Birthday { get; set; }
}
三、JSON序列化集合、字典、数组、DataTable的处理
可以使用JavaScriptSerializer类Serialize方法将数据源例序列化为JSON字符串。
在JSON数据中,所有的集合、字典、TataTable和数组都表示为数组。
(1)List<T>序列化:
private void Serialize()
{
List<Person> list = new List<Person>(){
new Person("Jason", "Chen", Convert.ToDateTime("1991-05-04")),
new Person("Jack", "Chen", Convert.ToDateTime("1991-05-05"))
};
string jsonString = JsonHelper.ToJson(list).ConvertToDateTimeString();
Response.Write(jsonString);
}
序列化结果:
[{"FirstName":"Jason","LastName":"Chen","Birthday":"1991-05-0400:00:00"},{"FirstName":"Jack","LastName":"Chen","Birthday":"1991-05-0500:00:00"}]
(2)Dictionary字典转化为JSON并不是跟原来的字典格式一致,而是形式以Dictionary的Key作为名称”Key“的值,以Dictionary的Value作为名称为”Value“的值。如:
private void Serialize()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("FirstName", "Jason");
dic.Add("LastName", "Chen");
string jsonString = JsonHelper.ToJson(dic);
Response.Write(jsonString);
}
序列化结果:
{"FirstName":"Jason","LastName":"Chen"}
(3)String数组序列化:
private void Serialize()
{
string[] ss = new string[] { "老婆", "小三" };
string jsonString = ss.ToJson();
Response.Write(jsonString);
}
序列化结果:
["老婆","小三"]
(4)DataTable序列化:
private void Serialize()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Rows.Add("1", "老婆", "40");
dt.Rows.Add("2", "小三", "20");
string jsonString = dt.ToJson();
Response.Write(jsonString);
}
序列化结果:
[{"Id":"1","Name":"老婆","Age":"40"},{"Id":"2","Name":"小三","Age":"20"}]
版权声明:本文为博主原创文章,未经博主允许不得转载。