常用代码之四:创建jason,jason转换为字符串,字符串转换回jason,c#反序列化jason****字符串的几个代码片段
创建jason,并JSON.stringify()将之转换为字符串。
直接使用var customer={}, 然后直接customer.属性就可以直接赋值了。
也可以var customer = { CustomerName: CustomerName, CustomerAddress: CustomerAddress } 这样创建,它会自动将:前面的CustomerName视作属性名并加上双引号,并将后面的CustomerName当作属性值,读取变量值后也加上双引号,当然,这不如上面的方式面向对象。
提交表单前,要使用JSON.stringify()方法将jason对象转换为字符串。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAppJason._Default" %>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
在C#中,引用system.web.extension.dll,并using System.Web.Script.Serialization,然后直接用JavaScriptSerializer的Deserialize方法把字符串反序列化为Customer对象使用了,非常简单方便。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
namespace WebAppJason
{
public class Customer {
public string CustomerName = "";
public string CustomerAddress = "";
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string custr = this.customer.Value;
if (custr != null && custr.Length > 0)
{
JavaScriptSerializer jsc = new JavaScriptSerializer();
Customer c = jsc.Deserialize(custr);
this.CustomerName0.Value = c.CustomerName;
this.CustomerAddress0.Value = c.CustomerAddress;
}
}
}
}
3.使用
JSON.parse()将字符串转回jason
function abc() {
var CustomerName = document.getElementById("CustomerName").value;
var CustomerAddress = document.getElementById("CustomerAddress").value;
var customer = {};
customer.CustomerName = CustomerName;
customer.CustomerAddress = CustomerAddress;
customer = JSON.stringify(customer);
//alert(customer);
var c2 = JSON.parse(customer);
alert(c2.CustomerName + " " + c2.CustomerAddress);
document.getElementById("customer").value = customer;
}