【.Net 】Json和Xml解析
引言
Json和Xml是现在跨平台传输数据的主流格式,关于它们的解析,网上资料很多,我稍作整理,写成一个小demo,方便日后使用.
JSON解析
能进行json解析的类库有很多,例如JavaScriptSerializer,DataContractJsonSerializer和开源类库Newtonsoft.Json.这里使用Newtonsoft.Json作个演示.
1.定义示例的类
public class Data { public string Name { get; set; } public int Jobnum { get; set; } public DateTime Date { get; set; } }
2.调用静态类JsonConvert进行序列化和反序列化,很简单,代码如下
List<Data> datas = new List<Data>(); datas.Add(new Data { Jobnum = 1, Name = "张三" ,Date=DateTime.Now}); datas.Add(new Data { Jobnum = 2, Name = "李四", Date = DateTime.Now }); string reslut= JsonConvert.SerializeObject(datas); List<Data> dataresult = JsonConvert.DeserializeObject<List<Data>>(reslut);
XML解析
1.xml解析需要用到XmlSerializer类,对象类要加上[Serializable],如下
[Serializable] public class Data { public string Name { get; set; } public int Jobnum { get; set; } public DateTime Date { get; set; } }
2.编写XMLSerialize静态解析类,代码如下
public static class XMLSerialize { public static string Serialize<T>(object obj) { XmlSerializer xml = new XmlSerializer(typeof(T)); using (StringWriter reader = new StringWriter()) { xml.Serialize(reader, obj); return reader.ToString(); } } public static T DeSerialize<T>(string xmlstr) { XmlSerializer xml = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xmlstr)) { return (T)xml.Deserialize(reader); } } }
3.调用静态类XMLSerialize方法进行序列和反序列化
List<Data> datas = new List<Data>(); datas.Add(new Data { Jobnum = 1, Name = "张三", Date = DateTime.Now }); datas.Add(new Data { Jobnum = 2, Name = "李四", Date = DateTime.Now }); string xmlstr = XMLSerialize.Serialize<List<Data>>(datas); List<Data> obj = XMLSerialize.DeSerialize<List<Data>>(xmlstr);
小结
本文是json和xml一个简单示例,用到了常用的解析方式,如果您有更好的方法,请不吝指教,感激不尽!