C#.NET序列化XML、JSON、二进制微软自带DLL与newtonsoft(json.net)
序列化是将对象转换成另一种格式(XML、json、二进制byte[])
JSON序列化
.NET中有三种常用的JSON序列化的类,分别是:
Newtonsoft.Json.JsonConvert类(推荐)
Newtonsoft.Json.JsonConvert类是非微软提供的一个JSON序列化和反序列的开源免费的类库(下载网址是:http://www.codeplex.com/json/),它提供了更灵活的序列化和反序列化控制,并且如果你的开发环境使用的是.NET Framework3.5及以后版本的话,你就可以使用Linq to JSON,这样一来面对一大段的数据不必一一解析,你可以使用Linq to JSON解析出你关心的那部分即可,非常方便。
下面是使用Newtonsoft.Json.JsonConvert类的例子:
public static void JsonConvertDemo() { User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.BelowNormal, Salary = 5000 }; //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 //JSON序列化 string result = JsonConvert.SerializeObject(user); Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); //JSON反序列化 user = JsonConvert.DeserializeObject<User>(result); Console.WriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); } public static void JsonConvertLinqDemo() { User user = new User { UserId = 1, UserName = "周公", CreateDate = DateTime.Now.AddYears(-8), Birthday = DateTime.Now.AddYears(-32), Priority = Priority.Lowest, Salary = 500, Urls = new List<string> { "http://zhoufoxcn.blog.51cto.com", "http://blog.csdn.net/zhoufoxcn" } }; //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 //JSON序列化 string result = JsonConvert.SerializeObject(user); Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); //使用Linq to JSON JObject jobject = JObject.Parse(result); JToken token = jobject["Urls"]; List<string> urlList = new List<string>(); foreach (JToken t in token) { urlList.Add(t.ToString()); } Console.Write("使用Linq to JSON反序列化后的结果:["); for (int i = 0; i < urlList.Count - 1;i++ ) { Console.Write(urlList[i] + ","); } Console.WriteLine(urlList[urlList.Count - 1] + "]"); }
注意:如果有不需要序列化的字段,可以给该字段添加[JsonIgnore]标记。在Newtonsoft这个类库中对于日期的序列化有多种方式,可以类的DataTime成员添加上对应的标记,这样在进行序列化和反序列化时就会按照指定的方式进行,在本例中User类的CreateDate属性添加的属性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday属性添加的属性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],从序列化的结果可以看出来它们最终的表现形式并不一样。
该实例完整代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; namespace JSONDemo { class Program { static void Main(string[] args) { JavaScriptSerializerDemo(); DataContractJsonSerializerDemo(); JsonConvertDemo(); JsonConvertLinqDemo(); Console.ReadLine(); } public static void JavaScriptSerializerDemo() { User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30),Birthday=DateTime.Now.AddYears(-50), Priority = Priority.Highest, Salary = 500000 }; //JavaScriptSerializer类在System.Web.Extensions.dll中,注意添加这个引用 JavaScriptSerializer serializer = new JavaScriptSerializer(); //JSON序列化 string result=serializer.Serialize(user); Console.WriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, result.Length); //JSON反序列化 user = serializer.Deserialize<User>(result); Console.WriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); } public static void DataContractJsonSerializerDemo() { User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.AboveNormal, Salary = 50000 }; string result = string.Empty; //DataContractJsonSerializer类在System.ServiceModel.Web.dll中,注意添加这个引用 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(User)); using (MemoryStream stream = new MemoryStream()) { //JSON序列化 serializer.WriteObject(stream, user); result = Encoding.UTF8.GetString(stream.ToArray()); Console.WriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, result.Length); } //JSON反序列化 byte[] buffer = Encoding.UTF8.GetBytes(result); using (MemoryStream stream = new MemoryStream(buffer)) { user = serializer.ReadObject(stream) as User; Console.WriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); } } public static void JsonConvertDemo() { User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.BelowNormal, Salary = 5000 }; //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 //JSON序列化 string result = JsonConvert.SerializeObject(user); Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); //JSON反序列化 user = JsonConvert.DeserializeObject<User>(result); Console.WriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); } public static void JsonConvertLinqDemo() { User user = new User { UserId = 1, UserName = "周公", CreateDate = DateTime.Now.AddYears(-8), Birthday = DateTime.Now.AddYears(-32), Priority = Priority.Lowest, Salary = 500, Urls = new List<string> { "http://zhoufoxcn.blog.51cto.com", "http://blog.csdn.net/zhoufoxcn" } }; //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 //JSON序列化 string result = JsonConvert.SerializeObject(user); Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); //使用Linq to JSON JObject jobject = JObject.Parse(result); JToken token = jobject["Urls"]; List<string> urlList = new List<string>(); foreach (JToken t in token) { urlList.Add(t.ToString()); } Console.Write("使用Linq to JSON反序列化后的结果:["); for (int i = 0; i < urlList.Count - 1;i++ ) { Console.Write(urlList[i] + ","); } Console.WriteLine(urlList[urlList.Count - 1] + "]"); } } [DataContract] public class User { /// <summary> /// 编号 /// </summary> [DataMember] public int UserId { get; set; } /// <summary> /// 用户名 /// </summary> [DataMember] public string UserName { get; set; } /// <summary> /// 创建时间 /// </summary> [DataMember] [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime CreateDate { get; set; } /// <summary> /// 生日 /// </summary> [DataMember] [JsonConverter(typeof(JavaScriptDateTimeConverter))] public DateTime Birthday { get; set; } /// <summary> /// 相关URL /// </summary> [DataMember] public List<string> Urls { get; set; } /// <summary> /// 薪水 /// </summary> [ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段 [IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段 [JsonIgnore]//使用JsonConvert序列化时不序列化此字段 public int Salary { get; set; } /// <summary> /// 权利级别 /// </summary> [DataMember] public Priority Priority { get; set; } public User() { Urls = new List<string>(); } } /// <summary> /// 权利级别 /// </summary> public enum Priority:byte { Lowest=0x1, BelowNormal=0x2, Normal=0x4, AboveNormal=0x8, Highest=0x16 } }
运行结果:
使用JavaScriptSerializer序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"\/Date(353521211984)\/","Birthday":"\/Date(-277630788015)\/","Urls":[],"Priority":22},长度:127 使用JavaScriptSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-15 16:20:11,Priority:Highest 使用DataContractJsonSerializer序列化后的结果:{"Birthday":"\/Date(-277630787953+0800)\/","CreateDate":"\/Date(353521212046+0800)\/","Priority":8,"Urls":[],"UserId":1,"UserName":"李刚"},长度:136 使用DataContractJsonSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:AboveNormal 使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"1981-03-16T00:20:12.1875+08:00","Birthday":new Date(-277630787812),"Urls":[],"Priority":2},长度:132 使用JsonConvert反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:BelowNormal 使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"周公","CreateDate":"2003-03-16T00:20:12.40625+08:00","Birthday":new Date(290362812406),"Urls":["http://zhoufoxcn.blog.51cto.com","http://blog.csdn.net/zhoufoxcn"],"Priority":1},长度:198 使用Linq to JSON反序列化后的结果:["http://zhoufoxcn.blog.51cto.com","http://blog.csdn.net/zhoufoxcn"]
System.Web.Script.Serialization.JavaScriptSerializer类
使用该类需要添加类库System.Web.Extensions.dll
namespace _03对象序列化 { class Program { static void Main(string[] args) { //序列化,就是把一个对象转换成另外一种格式的过程,转换成不同的格式就叫做不同的序列化,比如xml格式,叫做xml序列化。JavaScript的json格式,叫做JavaScript序列化。转换成二进制byte[]字节,叫做二进制序列化。 //序列化质序列化那些属性(或者说是序列化了对象中的状态信息(字段、属性就是用来存储状态的)),而方法并没有序列化。 //序列化后的目的,是为了把数据以另外一种格式来表示,方便存储与交换数据,所以序列化只序列化那些存储数据的成员,一般就是属性,不会序列化方法的。 //有序列化,就有反序列化 #region 对象序列化 //=1================================================= List<Person> list = new List<Person>(); list.Add(new Person() { Name = "余尚勇", Age = 19, Email = "ysh@yahoo.com" }); list.Add(new Person() { Name = "宋文斌", Age = 29, Email = "swb@yahoo.com" }); list.Add(new Person() { Name = "闫刘盘", Age = 16, Email = "ylp@yahoo.com" }); //使用JavaScript 序列化。 JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); string str = jsSerializer.Serialize(list); //jsSerializer.Deserialize();//反序列化 File.WriteAllText("list.txt", str); Console.WriteLine(str); Console.ReadKey(); ////二进制序列化 //BinaryFormatter bf = new BinaryFormatter(); //using (FileStream fsWrite = File.OpenWrite("list.bin")) //{ // bf.Serialize(fsWrite, list); // //bf.Deserialize();//反序列化 //} //Console.WriteLine("ok"); //Console.ReadKey(); ////xml序列化 ////XmlSerializer xmlSerializer = new XmlSerializer(list.GetType()); //XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Person>)); //using (FileStream fsWrite = File.OpenWrite("list.xml")) //{ // xmlSerializer.Serialize(fsWrite, list); // //xmlSerializer.Deserialize();//反序列化 //} //Console.WriteLine("ok"); //Console.ReadKey(); #endregion } } [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public void SayHi() { Console.WriteLine("大家好,我叫:{0}", Name); } public void SayHello() { Console.WriteLine("Hello"); } } }
System.Runtime.Serialization.Json.DataContractJsonSerializer类
参考资料:http://www.cnblogs.com/coderzh/archive/2008/11/25/1340862.html
添加类库“system.Web.Extensions.dll”
如果进行二进制序列化,不要用自动属性,是把属性对应的字段名(自动生成的,且不固定)序列化!
XML、二进制序列化要加标记[Serializable]包括该类的父类
如果不像序列化某字段 需要加标记no….
参考资料:http://zhoufoxcn.blog.51cto.com/792419/517093
解析多层嵌套:
using System; using Newtonsoft.Json.Linq; public partial class json : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string getJson ="{'data': {" +"'personal': {" +" 'name': '宋华勇'," +" 'sex': '男'," +" 'height':'175cm'," +" 'age':'30'," +" 'school':'厦门大学'" +"}," +" 'workplace':'汕头'," +" 'worktype':'前端工程师'" +" }" +"}"; string result = ""; var jObject = JObject.Parse(getJson); result = "大家好!我叫" + jObject["data"]["personal"]["name"].ToString()+",很高兴你们来到我的网站。希望我写的文章能帮助到你们!"; Response.Write(result); } }
多级嵌套
http://blog.csdn.net/smartsmile2012/article/details/17305503
//------------------------------------------------------------------------------------------------------
2015-3-21
XML写入
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace _01写入xml文件 { class Program { static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person() { Age = 18, Gender = "男", Name = "张三" , Id="110"}); list.Add(new Person() { Age = 19, Gender = "女", Name = "龙太子", Id = "111" }); list.Add(new Person() { Age = 20, Gender = "中", Name = "小黑", Id = "112" }); XDocument xdoc = new XDocument(); //创建根元素 XElement root = new XElement("Person"); for (int i = 0; i < list.Count; i++) { //创建子节点 XElement student = new XElement("student"); student.SetAttributeValue("Id",list[i].Id); student.SetElementValue("name",list[i].Name); student.SetElementValue("gender",list[i].Gender); student.SetElementValue("age",list[i].Age.ToString()); root.Add(student);//节点添加到根节点中 } //把根元素添加到文件中 xdoc.Add(root); //保存 xdoc.Save("person.xml"); } } class Person { string _id; public string Id { get { return _id; } set { _id = value; } } string _name; public string Name { get { return _name; } set { _name = value; } } int _age; public int Age { get { return _age; } set { _age = value; } } string _gender; public string Gender { get { return _gender; } set { _gender = value; } } } }
XML读取
XDocument xdoc= XDocument.Load("bank.xml");
//遍历根节点下所有的子节点
foreach (XElement item in xdoc.Root.Elements())
{
Console.WriteLine(item.Name);
foreach (XElement ele in item.Elements())
{
Console.WriteLine(ele.Name+"==="+ele.Attribute("val").Value);
}
}
Console.ReadKey();
XML遍历
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
namespace _03遍历xml文件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//读取xml文件
XDocument xdoc= XDocument.Load("11.xml");
XElement root = xdoc.Root;//获取根元素
TreeNode tn= tv.Nodes.Add(root.Name.ToString());//根元素的名字显示到控件的根节点上
LoadXElement(root,tn);
}
private void LoadXElement(XElement root, TreeNode tn)
{
//遍历根元素下所有的子元素
foreach (XElement item in root.Elements())
{
//判断当前的元素下是否还有元素
if (item.Elements().Count() > 0)
{
TreeNode tn1 = tn.Nodes.Add(item.Name.ToString());
LoadXElement(item, tn1);
}
else
{
tn.Nodes.Add(item.Value);
}
}
}
}
}
源码在图片里
JSON
[{"ID":"92976A17-4AB2-453E-85BA-90944046C4A4","CompetitionID":"A5D4AD79-2F8B-6645-23D3-3A79D076D5A3","PrizeNO":"设计奖","PrizeInfo":"iPhone 6","PrizeNum":"1","ListIndex":"1","Remark":"备注","PrizeLevel":"一等奖","ID1516":"1"},{"ID":"D12A4E98-A429-48B8-BF07-E0309BCE1AD3","CompetitionID":"A5D4AD79-2F8B-6645-23D3-3A79D076D5A3","PrizeNO":"创意奖","PrizeInfo":"iPhone6","PrizeNum":"1","ListIndex":"1","Remark":"备注","PrizeLevel":"一等奖","ID1516":"2"},{"ID":"D76E2F46-E2E0-4EE9-B809-AE9D5A989D09","CompetitionID":"A5D4AD79-2F8B-6645-23D3-3A79D076D5A3","PrizeNO":"创意奖","PrizeInfo":"iPhone 5","PrizeNum":"1","ListIndex":"2","Remark":"备注","PrizeLevel":"二等奖","ID1516":"3"},{"ID":"121B85ED-EA39-4D22-BD6B-3CDD67B14254","CompetitionID":"A5D4AD79-2F8B-6645-23D3-3A79D076D5A3","PrizeNO":"设计奖","PrizeInfo":"iPhone 5","PrizeNum":"1","ListIndex":"2","Remark":"备注","PrizeLevel":"二等奖","ID1516":"4"}]
//工作竞赛-课题发布-获取奖项列表 var getList_CompetitionPrize = function () { var par_edit = { 'OperID': MemberInfo.MemberID, //操作人ID 'CompetitionID': CompetitionInfo.ID, //我的工作ID }; GLOBAL.DataStore.DataHandle.postData({ url: _pagebase.ServiceURL, handler: 'Web_Task_perm', parame: '{fucid:"GetList_CompetitionPrize",data:"' + encodeURIComponent(encodeURIComponent(JSON.stringify(par_edit))) + '"}', success: function (result) { if (result.errcode === 0) { alert(JSON.stringify(result.data)) var mydata = {}; $.each(result.data, function (index, item) { if (!mydata[item["PrizeNO"]]) { mydata[item["PrizeNO"]] = []; } mydata[item["PrizeNO"]].push(item); }) var htmlPrize = ''; var _tempHtml = $("#temp_PrizeList").html(); $.each(mydata, function (index, item) { htmlPrize += '<h2>' + index + '</h2>'; for (var i = 0; i < item.length; i++) { var PrizeModel = item[i]; htmlPrize += _tempHtml.replaceData(PrizeModel); } }) document.querySelector('#div_prizelist').innerHTML = htmlPrize; } else { } } }); }
unicode
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft; using System.IO; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person() { Name = "余尚勇", Age = 19, Email = "ysh@yahoo.com" }); list.Add(new Person() { Name = "宋文斌", Age = 29, Email = "swb@yahoo.com" }); list.Add(new Person() { Name = "闫刘盘", Age = 16, Email = "ylp@yahoo.com" }); string str = Newtonsoft.Json.JsonConvert.SerializeObject(list, new Newtonsoft.Json.JsonSerializerSettings() { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii }); //str = Unicode2String(str); File.WriteAllText("list.txt", str); var users =Newtonsoft.Json.JsonConvert.DeserializeObject<List<Person>>(str); foreach (var item in users) { Console.WriteLine(item.Name); } Console.WriteLine(str); Console.ReadKey(); } /// <summary> /// 字符串转Unicode /// </summary> /// <param name="source">源字符串</param> /// <returns>Unicode编码后的字符串</returns> internal static string String2Unicode(string source) { var bytes = Encoding.Unicode.GetBytes(source); var stringBuilder = new StringBuilder(); for (var i = 0; i < bytes.Length; i += 2) { stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0')); } return stringBuilder.ToString(); } /// <summary> /// Unicode转字符串 /// </summary> /// <param name="source">经过Unicode编码的字符串</param> /// <returns>正常字符串</returns> internal static string Unicode2String(string source) { return new System.Text.RegularExpressions.Regex(@"\\u([0-9A-F]{4})", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled).Replace(source, x => Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)).ToString()); } } [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public void SayHi() { Console.WriteLine("大家好,我叫:{0}", Name); } public void SayHello() { Console.WriteLine("Hello"); } } }
json 转 动态类型dynamic
string result = @"{""foo"":""json"", ""bar"":100, ""nest"":{ ""foobar"":true } }"; dynamic user = JsonConvert.DeserializeObject<dynamic>(result); Console.WriteLine(user.nest.foobar);