C # XML and JSON serialization and deserialization

Source: Internet
Author: User
Tags json serialization

serialization and deserialization of 1.JSON





JSON (JavaScript Object notation) is a lightweight data exchange language that, while a subset of JavaScript, is a language-independent text format. Its data format is relatively simple, easy to read and write, and are compressed, occupy a small bandwidth and easy to parse, usually in JSON format to transfer data or for data storage. More knowledge of the JSON data structure syntax you can learn from other places on the web, as long as we remember to use it often when the server is transferring data to the client, and then the serialization and deserialization of it is well worth knowing. The process of serialization is to convert an entity class object into a JSON string object, which directly consists of the attribute name and attribute value of the entity class as the "name/value" format, and the reverse serialization process. (I slag one, about these more formal language is not too will say, and then some directly moved is the book I read the text slightly)





Serialization and deserialization here, we all learn two ways of One is DataContractJsonSerializer (located under the System.Runtime.Serialization.Json namespace) and the other is Jsonobject and Jsonarray ( Located under the Windows.Data.Json namespace). The following is a specific demo:





Serialization:





First we define an entity class (Student.cs) with IDs, Nam, age three attributes, Gettestdata () to return the test data.








public class Student


{


public string Id {get; set;}


public string Name {get; set;}


public int Age {get; set;}





public static list<student> Gettestdata ()


{


list<student> studentlist = new list<student> ();


Studentlist.add (New Student () {Id = "201313138063", Name = "czhhhh", age = 18});


Studentlist.add (New Student () {Id = "201313138033", Name = "Xxxxzh", age = 22});


Studentlist.add (New Student () {Id = "201313138045", Name = "Wwwko", age = 19});


Studentlist.add (New Student () {Id = "201313138028", Name = "Marrio", age = 19});


Studentlist.add (New Student () {Id = "201313138016", Name = "Mike", age = 20});


return studentlist;


}


}








Then you can do the serialization: Look at the code below (method one or two comment out one), the note is written in detail. (True nonsense ~ ~)








private void InitData ()


{





list<student> studentlist = Student.gettestdata (); Get test data





Serialization JSON method One:


DataContractJsonSerializer Seriliazer = new DataContractJsonSerializer (studentlist. GetType ());


Requires a type value, because we want to serialize a list of data, directly take


Student list to studentlist. GetType (), here we should understand the difference between TypeOf and GetType ()





using (MemoryStream ms=new MemoryStream ())


{


Seriliazer. WriteObject (MS, studentlist);


Writeobject:serializes a specified object to JSON data


and writes the resulting JSON to a stream. (Serializes and writes)





Ms. Position = 0; Note that this is necessary because the last step of the operation


The position value of MS in will point to the end of the stream, for subsequent reads must be moved to the beginning





using (StreamReader reader=new StreamReader (ms))//reading data from the stream


{


Tb. Text = reader. ReadToEnd (); To display the data that is read


}


}





Serialization JSON method Two:


Jsonarray Stujsonarray = new Jsonarray ();


We want to serialize a set of data (list<student>), so we need to use the Jsonarray


Here Jsonarray corresponds to List<student&gt, while jsonobject corresponds to Student





foreach (Var stu in Studentlist)


{


Jsonobject Stujson = new Jsonobject ();


Stujson. Setnamedvalue ("id", Jsonvalue.createstringvalue (Stu).  ID)); Name-value Key value pairs


Stujson. Setnamedvalue ("Name", Jsonvalue.createstringvalue (Stu). Name));


Stujson. Setnamedvalue ("Age", Jsonvalue.createnumbervalue (Stu). Age));


Stujsonarray. ADD (Stujson); Add the Jsonobject object to the Jsonarray


}


Tb. Text = Stujsonarray.   Stringify (); Call Stringify () returns the JSON representation of the encapsulated value to display


}


Look at the result of serialization:










deserialization:





We save the JSON data that we serialized above to a file (Student.txt) and copy it to the project folder for deserialization.








Private async void Initdedata ()


{


Read JSON to string text from the project folder


Storagefolder installfolder = Windows.ApplicationModel.Package.Current.InstalledLocation;


Storagefile Storagefile = await Installfolder.getfileasync ("Student.txt");


String text = await Fileio.readtextasync (storagefile);





list<student> stulist = new list<student> ();





Deserialize JSON method one


DataContractJsonSerializer Seriliazer = new DataContractJsonSerializer (typeof (List<student>));





Converts a JSON string to byte [] to be instantiated as a parameter MemoryStream


using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (text))


// {


Stulist = Seriliazer. ReadObject (ms) as list<student>;


Reads a document stream in the JSON (JavaScript Object notation) format


and returns the deserialized object. (Read and return)


Cast into list<student>


// }


Listview.itemssource = stulist; Bind to the ListView control for presentation





Deserialize JSON method two


Jsonarray Jsonarray = jsonarray.parse (text); Converts a JSON string into a Jsonarray


(Because our JSON string is a data consisting of multiple objects, a single object is Jsonobjcet.parse)


for (int i = 0; i < Jsonarray. Count; i++)


{


Jsonobject jsonobj = Jsonarray. Getobjectat ((UINT) i);





Fetching data from a key-value pair


Stulist. ADD (New Student () {Id = Jsonobj. Getnamedstring ("Id"),


Name = Jsonobj. Getnamedstring ("Name"),


age = (int) jsonobj. Getnamednumber ("Age")});


}


Listview.itemssource = stulist;


}







See the result of deserialization:











serialization and deserialization of 2.XML





XML (extensible Markup Language, Extensible Markup Language) can be used to create content and then be labeled with a qualifying tag to make each phrase, block, and to be identifiable, classified information. It is an easy-to-use and extensible Markup language that can be used for data transmission and storage as well as JSON, but is more widely used than JSON and is a simple data storage format. For more detailed information about XML syntax you can learn about it online.





Like the above JSON operation, XML serialization and deserialization are done in two ways, One is the DataContractSerializer class under the System.Runtime.Serialization namespace, the other is the XmlDocument under the Windows.Data.Xml.Dom namespace, and the specific operation method and JSON are also class , Here's a demo:





Serialization:





First we have to define an entity class (Book.cs) and Gettestdata return the test data.








public class Book


{


public string Name {get; set;}


public string Author {get; set;}


public string ISBN {get; set;}


Public decimal price {get; set;}


public static list<book> Gettestdata ()


{


list<book> Booklist = new list<book> ();


Booklist. ADD (new book () {Name = "Home", Author = "Ba Jin", Isbn = "9787020058594", Price = 25.00M});


Booklist. ADD (new book () {Name = "Hilbert Geometry foundation", Author = "Hilbert", ISBN = "9787301148037", Price = 69.00M});


Booklist. ADD (new book () {Name = "mathematical principle of Natural philosophy", Author = "Newton", ISBN = "9787301095515", Price = 45.00M});


Booklist. ADD (new book () {Name = "effective Manager", Author = "Drucker", ISBN = "9787111280712", Price = 55.00M});


Booklist. ADD (new book () {Name = "Age of Revolution", Author = "Gaohua", ISBN = "9787218061948", Price = 35.00M});


return Booklist;


}


}











Then look at the specific serialization operation: Note the regularity of method two (first books, then add the book,book inside books, there are various attributes)








Private async void InitData ()


{


List<book> Booklist = Book.gettestdata ();





Serialization method One: This is similar to serialized JSON (DataContractJsonSerializer).


DataContractSerializer serializer = new DataContractSerializer (Booklist. GetType ());


using (MemoryStream ms = new MemoryStream ())


{


Serializer. WriteObject (MS, Booklist);


Ms. Position = 0;


using (StreamReader reader = new StreamReader (ms))


{


Tb. Text = reader. ReadToEnd ();


}


}





Serialization Method Two:


XmlDocument xdoc = new XmlDocument ();


XmlElement books = Xdoc. CreateElement ("books");


Xdoc. AppendChild (books);





foreach (Var book in Booklist)


//{


XmlElement Book1 = Xdoc. CreateElement ("book");





XmlElement name = Xdoc. createelement ("name");


Name. innertext = Book. Name;


Book1. AppendChild (name);





XmlElement author = xdoc. CreateElement ("author");


Author. innertext = Book. Author;


Book1. AppendChild (author);





XmlElement ISBN = Xdoc. CreateElement ("ISBN");


Isbn.innertext = Book. ISBN;


Book1. AppendChild (ISBN);





XmlElement price = Xdoc. CreateElement ("Price");


Price.innertext = Book. Price.tostring ();


Book1. AppendChild (price);





Books. AppendChild (BOOK1);


//}





Storagefile file = await ApplicationData.Current.LocalFolder.CreateFileAsync ("Book.xml",


creationcollisionoption.replaceexisting);


Await Xdoc. Savetofileasync (file);





if (file!= null)


//{


Tb. Text = await fileio.readtextasync (file);


//}


}











Again, is the result of serialization. (We are all inline attributes, the key= of "value")








deserialization:





We've saved the serialized data into an XML file (Book.xml) in the serialization process, so we'll serialize the XML file. It should be noted here that the DataContractSerializer class can deserialize its own serialized data only by deserializing it. That is, the book.xml stored after the XmlDocument class serialization is not able to deserialize it, I tried for a long time is abnormal, finally realized this.





Method Two seems to have more code, in fact, as long as we have mastered the parameters of selectnodes XPath writing, and then debugging, rapid monitoring, according to the specific XML to do the corresponding operation is almost. The generality of this method is relatively high, the XmlDocument series class also provides more methods, it is necessary to master skillfully.








List<book> Booklist = Book.gettestdata ();





Serialization method One: This is similar to serialized JSON (DataContractJsonSerializer).


DataContractSerializer serializer = new DataContractSerializer (Booklist. GetType ());


using (MemoryStream ms = new MemoryStream ())


{


Serializer. WriteObject (MS, Booklist);


Ms. Position = 0;


using (StreamReader reader = new StreamReader (ms))


{


Tb. Text = reader. ReadToEnd ();


}


}





Deserialization XML Method One


using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes) (TB. Text))


{


DataContractSerializer deserializer = new DataContractSerializer (typeof (List<book>));


Ms. Position = 0;//this don't forget!!!


Booklist = Deserializer. ReadObject (ms) as list<book>;


}


Listview.itemssource = Booklist;








Deserialization XML Method Two


XmlDocument xdoc = new XmlDocument ();


Xdoc. Loadxml (text);


XmlNodeList nodelist = Xdoc. SelectNodes ("Books/book");


foreach (var node in nodelist)


{


XmlElement XE = (xmlelement) node;


Booklist. ADD (new book ()


{


Name = Xe. Childnodes.item (0). InnerText,


Author = Xe. Childnodes.item (1). InnerText,


ISBN = Xe. Childnodes.item (2). InnerText,


Price = Convert.todecimal (XE. Childnodes.item (3). InnerText)


});


}


Listview.itemssource = Booklist;











The following is the result of the method one:






This is some of the content of XML and JSON serialization and deserialization.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.