using System;
using System.Collections.Generic;
using System.Web.Script.Serialization; //引用序列化类库
public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// 应对 Json.NET 使用序列化和反序列化。 为启用 AJAX 的应用程序提供序列化和反序列化功能。
/// ByYlbtech
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
var RegisteredUsers = new List<Person>();
RegisteredUsers.Add(new Person() { PersonID = 1, Name = "Bryon Hetrick", Registered = true });
RegisteredUsers.Add(new Person() { PersonID = 2, Name = "Nicole Wilcox", Registered = true });
RegisteredUsers.Add(new Person() { PersonID = 3, Name = "Adrian Martinson", Registered = false });
RegisteredUsers.Add(new Person() { PersonID = 4, Name = "Nora Osborn", Registered = false });
// 1、创建JavaScriptSerializer
var serializer = new JavaScriptSerializer();
// 2、序列化
// 将对象转换为 JSON 字符串
var serializedResult = serializer.Serialize(RegisteredUsers);
// Produces string value of:
// [
// {"PersonID":1,"Name":"Bryon Hetrick","Registered":true},
// {"PersonID":2,"Name":"Nicole Wilcox","Registered":true},
// {"PersonID":3,"Name":"Adrian Martinson","Registered":false},
// {"PersonID":4,"Name":"Nora Osborn","Registered":false}
// ]
// 3、反序列化
// 将指定的 JSON 字符串转换为 T 类型的对象
var deserializedResult = serializer.Deserialize<List<Person>>(serializedResult);
// Produces List with 4 Person objects
}
/// <summary>
/// Person实体类
/// </summary>
public class Person {
/// <summary>
/// 编号【PK】
/// </summary>
public int PersonID { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 是否注册
/// </summary>
public bool Registered { get; set; }
}
}