標籤:.net中json的序列化與還原序列化
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>
:650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/4D/B3/wKioL1RXhF_BcvoIAADfqom1PAw324.jpg" title="QQ20141103213108.jpg" alt="wKioL1RXhF_BcvoIAADfqom1PAw324.jpg" />
本文出自 “Day Day Up” 部落格,請務必保留此出處http://1433189426.blog.51cto.com/8055494/1571439
.net中JSON的序列化與還原序列化