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>
效果图:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。