前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="JSonExercise.WebForm1" validateRequest="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> 将Customer类转成string :<asp:TextBox ID="rT1" runat="server" TextMode="MultiLine" Width="600px" Height="150"></asp:TextBox> <br /> 读txt文件并转成Customer类:<asp:TextBox ID="txtCustomer" runat="server" TextMode="MultiLine" Width="600" Height="150"></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Json类序列化string" /> <br /> <br /> <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="读txt文件发序列化Custom类" /> </div> </form> </body> </html>
后台代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Xml.Serialization; namespace JSonExercise { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public class Customer { public int Unid { get; set; } public string CustomerName { get; set; } } // 将实体转成string public string ToJson(Customer customer) { string strReturn = SerializeToXml(customer); return strReturn; } protected void Button1_Click(object sender, EventArgs e) { Customer cc = new Customer { Unid = 1, CustomerName = "John" }; string strJson = ToJson(cc); rT1.Text = strJson; } #region 实现对象转换成XML类型字符串。 /// <summary> /// 实现对象转换成XML类型字符串。 /// </summary> /// <param name="obj">Object对象参数</param> /// <returns>返回XML类型字符串</returns> public static string SerializeToXml(object obj) { XmlSerializer s = new XmlSerializer(obj.GetType()); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); s.Serialize(writer, obj); return sb.ToString().Replace(@"\>\s+", ">"); } #endregion #region 实现Xml字符串转换为实体对象。 /// <summary> /// 实现Xml字符串转换为实体对象。 /// </summary> /// <typeparam name="T">实体对象的类型</typeparam> /// <param name="xmlObject">xml字符串</param> /// <returns>返回对应的实体对象</returns> public static T DeserializeXmlString<T>(string xmlObject) { XmlSerializer s = new XmlSerializer(typeof(T)); StringReader stringReader = new StringReader(xmlObject); return (T)s.Deserialize(stringReader); } #endregion protected void Button2_Click(object sender, EventArgs e) { FileStream fs1 = new FileStream("customer.txt", FileMode.Open); StreamReader sr = new StreamReader(fs1); string str1 = sr.ReadToEnd(); sr.Close(); fs1.Close(); Customer customer = DeserializeXmlString<Customer>(str1); txtCustomer.Text = customer.Unid + " " + customer.CustomerName; } } }