C#完成的json序列化和反序列化代碼實例。本站提示廣大學習愛好者:(C#完成的json序列化和反序列化代碼實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成的json序列化和反序列化代碼實例正文
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
namespace WebApplication1
{
//辦法一:引入System.Web.Script.Serialization定名空間應用 JavaScriptSerializer類完成簡略的序列化
[Serializable]
public class Person
{
private int id;
/// <summary>
/// id
/// </summary>
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
/// <summary>
/// 姓名
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
}
//辦法二:引入 System.Runtime.Serialization.Json定名空間應用 DataContractJsonSerializer類完成序列化
//可使用IgnoreDataMember:指定該成員不是數據協議的一部門且沒有停止序列化,DataMember:界說序列化屬性參數,應用DataMember屬性標志字段必需應用DataContract標志類 不然DataMember標志不起感化。
[DataContract]
public class Person1
{
[IgnoreDataMember]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "sex")]
public string Sex { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Person p1 = new Person();
p1.Id = 1;
p1.Name = "dxw";
Person p2 = new Person();
p2.Id = 2;
p2.Name = "wn";
List<Person> listperson = new List<Person>();
listperson.Add(p1);
listperson.Add(p2);
JavaScriptSerializer js = new JavaScriptSerializer();
//json序列化
string s = js.Serialize(listperson);
Response.Write(s);
//辦法二
Person1 p11 = new Person1();
p11.Id = 1;
p11.Name = "hello";
p11.Sex = "男";
DataContractJsonSerializer json = new DataContractJsonSerializer(p11.GetType());
string szJson = "";
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, p11);
szJson = Encoding.UTF8.GetString(stream.ToArray());
Response.Write(szJson);
}
//反序列化
//using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
//{
// DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
// Person1 _people = (Person1)serializer.ReadObject(ms);
//}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(constr);
}
}