Penson类
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Json_Demo { public class Penson { private string _name; private int _age; private string _address; public string Address { get { return _address; } set { _address = value; } } public int Age { get { return _age; } set { if (_age < 100 && _age > 0) { _age = value; } else { _age = 0; } } } public string Name { get { return _name; } set { _name = value; } } } }
后台代码:
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; using System.Web.Script.Serialization; namespace Json_Demo { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Penson p1 = new Penson(); p1.Name = "JSON"; p1.Age = 120; p1.Address = "江西高安"; JavaScriptSerializer json1 = new JavaScriptSerializer(); string str = json1.Serialize(p1);//JSON序列化 Session["str1"] = str;//session页面传值 } } } 前台 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Json_Demo.WebForm1" %> //导入命名空间 <%@ Import Namespace="Json_Demo" %> <%@ Import Namespace="System.Web.Script.Serialization" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form id="form1" runat="server"> <div> <% string s = (string)Session["str1"]; Response.Write(s);%> <br /> <% Penson p1 = new Penson(); JavaScriptSerializer str2 = new JavaScriptSerializer(); //JSON反序列化 p1 = str2.Deserialize<Penson>(s); Response.Write(p1.Name + p1.Age + p1.Address); %> </div> </form> </body> </html>
本文出自 “Day Day Up” 博客,请务必保留此出处http://1433189426.blog.51cto.com/8055494/1571439
原文地址:http://1433189426.blog.51cto.com/8055494/1571439