c/c++常用程式碼之四爆炸輸出,jason(純乾貨)
常用程式碼之四:建立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" %>
<head runat="server">
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">
function abc() {
var customer = {};
customer.CustomerName = document.getElementById("CustomerName").value;
customer.CustomerAddress = document.getElementById("CustomerAddress").value;
customer = JSON.stringify(customer);
//alert(customer);
document.getElementById("customer").value = customer;
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<input type="text" id="CustomerName" />
<input type="text" id="CustomerAddress" />
<input type="text" id="customer" runat="server" />
<input type="button" id="button1" value="button1" onclick="abc()" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
<input type="text" id="CustomerName0" runat="server" />
<input type="text" id="CustomerAddress0" runat="server" /></div>
</form>
</body>
</html>
2.
在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<Customer>(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;
}
文末也給大家,分享主要有C/C++,Linux,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,TCP/IP,協程,DPDK技術,面試技巧方面的資料技術討論。
感興趣的朋友可以加群:812855908
出處:http://www.cn