在Web中开发中经常要在前端将对象或对象集合进行序列化字符串后传给后台,再由后台反序列化后再操作。可参考以下方法:
一、前端JavaScript序列化
//产品
var product = { "ItemNo": "1001", "ItemName": "三星手机", "SaleTime": "2014-11-11", "Price": "1800" };
//利用 JSON.stringify 序列化对象(键值对集合), 变成字符串
var product_str = JSON.stringify(product);
//学生
var students = [
{ "No": "A01", "Name": "陈小明", "Birthday": "2001-08-15", "Height": "172" },
{ "No": "B01", "Name": "韦春花", "Birthday": "2001-10-20", "Height": "160" }
];
//利用 JSON.stringify 序列化对象集合, 变成字符串
var students_str = JSON.stringify(students);
二、后台C#反序列化
//利用JSON.Decode将对象(键值对集合)字符串反序列化成 Dictionary
var dict = (Dictionary<string, object>) JSON.Decode(product, typeof(Dictionary<string, object>));
string productInfo = "";
if (dict.ContainsKey("ItemName")) //可以用ContainsKey 判断是否有该键(Key)
{
productInfo = "名称: " + dict["ItemName"];
}
if (dict.ContainsKey("SaleTime") && dict["SaleTime"] != null)
{
if (dict["SaleTime"].GetType().ToString() == "System.DateTime")
{
productInfo += "开卖日期:" + ((DateTime)dict["SaleTime"]).ToString("yyyy-MM-dd");
}
}
//利用JSON.Decode将对象集合字符串反序更化成 ArrayList, 用 Hashtable 进行逐一对象读取
var studentsList = (ArrayList)JSON.Decode(students);
foreach (Hashtable student in studentsList)
{
var no = student["No"];
var name = student["Name"];
var birthday = student["Birthday"];
}