Introduction
JSON and XML is now a cross-platform transmission of data in the mainstream format, about their analysis, the online data a lot, I do a little collation, write a small demo, convenient for later use.
JSON parsing
There are many class libraries that can parse the JSON, such as JavaScriptSerializer, DataContractJsonSerializer and open source class library Newtonsoft.json. Here's a demo using Newtonsoft.json.
1. Classes that define the example
Public class Data { publicstringgetset;} Public int Get Set ; } Public Get Set ; } }
2. Call the static class JsonConvert for serialization and deserialization, very simple, the code is as follows
list<data> datas = (); Datas. ADD ( new Data {jobnum = 1 , Name = Span style= "color: #800000;" > " Zhang San " , Date=datetime.now}); Datas. ADD ( new Data {jobnum = 2 , Name = Span style= "color: #800000;" > " John Doe " , Date = DateTime.Now}); string reslut= Jsonconvert.serializeobject (datas); List <Data> dataresult = jsonconvert.deserializeobject<list<data>> (reslut);
XML parsing
1.XML parsing needs to use the XmlSerializer class, the object class to add [Serializable], as follows
[Serializable] publicclass Data { public Stringgetset;} Public int Get Set ; } Public Get Set ; } }
2. Write xmlserialize static parsing class, the code is as follows
Public Static classXmlserialize { Public Static stringSerialize<t> (Objectobj) {XmlSerializer XML=NewXmlSerializer (typeof(T)); using(StringWriter reader =NewStringWriter ()) {XML. Serialize (reader, obj); returnReader. ToString (); } } Public StaticT deserialize<t> (stringxmlstr) {XmlSerializer XML=NewXmlSerializer (typeof(T)); using(StringReader reader =NewStringReader (XMLSTR)) { return(T) XML. Deserialize (reader); } } }
3. Call the static class Xmlserialize method for sequence and deserialization
list<data> datas =NewList<data>(); Datas. ADD (NewData {jobnum =1, Name ="Zhang San", Date =DateTime.Now}); Datas. ADD (NewData {jobnum =2, Name ="John Doe", Date =DateTime.Now}); stringXmlstr = xmlserialize.serialize<list<data>>(datas); List<Data> obj = xmlserialize.deserialize<list<data>> (XMLSTR);
Summary
This article is a simple example of JSON and XML, using the usual parsing methods, if you have a better way, please feel free, thank you!
. NET JSON and XML parsing