一、XML格式装换成json数据格式
using System; using System.Collections.Generic; using System.Linq; using System.Web; //要使用JavaScriptSerializer需添加这个using System.Web.Script.Serialization;引用 using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; //要使用XDocument需添加这个using System.Xml.Linq引用 using System.Xml.Linq; //要使用JsonConvert需添加这个Newtonsoft.Json.dll引用 using Newtonsoft.Json; using System.Xml; public partial class xmlchange : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var xml = @"<Columns> <Column Name=""key1"">key1</Column> <Column Name=""key2"">key2</Column> <Column Name=""key3"">key3</Column> </Columns>"; var dic = XDocument .Parse(xml) .Descendants("Column") .ToDictionary( c => c.Attribute("Name").Value, c => c.Value ); var json = new JavaScriptSerializer().Serialize(dic); Label1.Text = json; xml model = JsonConvert.DeserializeObject<xml>(json); Label2.Text = model.key1; Label3.Text = model.key2; Label4.Text = model.key3; } public class xml { public string key1 { get; set; } public string key2 { get; set; } public string key3 { get; set; } } }
二,json数据格式的序列化和反序列化
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; public partial class jsonchange : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { test te = new test(); te.test1 = 1; te.test2 = "test"; JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 string r1 = jsonSerializer.Serialize(te); Label1.Text =r1; //执行反序列化 test per = jsonSerializer.Deserialize<test>(r1); Label2.Text = per.test1.ToString(); Label3.Text = per.test2; } public class test { public int test1 { get; set; } public string test2 { get; set; } } }
时间: 2024-10-10 04:27:28