@序列化:即将类对象或者泛型列表对象转换为json格式。
@反序列化:即将JSON格式数据转换为类对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
namespace huoyunxianTest
{
/// <summary>
///
/// </summary>
public partial class TestJson2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//声明一个数组格式的json字符串
var txt = @"{""employees"" : [
{ ""firstName"":""Bill"" , ""lastName"":""Gates"" },{ ""firstName"":""George"" , ""lastName"":""Bush"" },
{ ""firstName"":""Thomas"" , ""lastName"":""Carter"" } ]}";
OutClass oc = new OutClass();
List<InClass> outclass=new List<InClass>();
oc.employees = outclass;//类型字段赋值
//***************将json数据反序列化为对象,OutClass是对象的类型******************
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(OutClass));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(txt)))
{
----ReadObject以Json格式读取文档流,并返回反序列化对象(即对应的接受类-容器。)
OutClass o1 = ser1.ReadObject(ms) as OutClass;
----下边是将反序列化后得到的对象,写入到对应的泛型类中
foreach (var i in o1.employees)
{
outclass.Add(i);
}
Response.Write(outclass[0].firstName);
Response.Write(outclass[0].lastName);
Response.Write("<br />*****************************<br/>");
Response.Write("数组序号为0的firstName是:" + o1.employees[0].firstName + "<br />数组序号为1的firstName是:" + o1.employees[1].firstName + "<br />数组序号为2的firstName是:" + o1.employees[2].firstName + "<br />");
Response.Write("数组序号为0的lastName是:" + o1.employees[0].lastName + "<br />数组序号为1的lastName是:" + o1.employees[1].lastName + "<br />数组序号为2的lastName是:" + o1.employees[2].lastName);
}
//******************这里是将类型为OutClass的oc对象转换为json格式。*******************
string json3 = GetJSON<OutClass>(oc);
Response.Write(json3);
//******************这里是将类型为InClass的泛型列表outclass转换为json格式。*************
//string json2 = JSON<InClass>(outclass);
//Response.Write(json2);
}
/// <summary>
/// 转换对象为JSON格式数据
/// </summary>
/// <typeparam name="T">转换对象的类型</typeparam>
/// <param name="obj">待转换对象</param>
/// <returns>字符格式的JSON数据</returns>
public static string GetJSON<T>(object obj)
{
string result = String.Empty;
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, obj);
result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
/// <summary>
/// 转换List<T>的数据为JSON格式
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="vals">列表值</param>
/// <returns>JSON格式数据</returns>
public static string JSON<T>(List<T> vals)
{
System.Text.StringBuilder st = new System.Text.StringBuilder();
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
foreach (T city in vals)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
s.WriteObject(ms, city);
st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
}
}
}
catch (Exception ex)
{
throw ex;
}
return st.ToString();
}
}
//备注:C#中对于实体对象的序列化,其实就是字符串拼接。下边的效果和上边的转换效果一样。
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var j in list)
{
if (j != list[list.Count - 1])
{
sb.Append("{\"key\":\"" + j.key + "\",\"value\":\"" + j.value + "\"},");
}
else
{
sb.Append("{\"key\":\"" + j.key + "\",\"value\":\"" + j.value + "\"}");
}
}
sb.Append("]");
return sb.ToString();
[Serializable]
public class OutClass
{
//上边employees的值是个数组,所以对应用泛型类列表表示。
private List<InClass> Employees;
public List<InClass> employees
{
get { return Employees; }
set { Employees = value; }
}
}
[Serializable]
public class InClass
{
private string FirstName;
public string firstName
{
get { return FirstName; }
set { FirstName = value; }
}
private string LastName;
public string lastName
{
get { return LastName; }
set { LastName = value; }
}
}
}