In the previous section, we discussed how to manually process JSON object data. You may also find that it is a bit painful. So, how can I read and write JSON data? Yes. If you have played with WCF, you may have thought of JSON serialization and deserialization.
The datacontractjsonserializer class is located in the namespace of system. runtime. serialization. JSON. We only need to call two methods to complete serialization and deserialization.
Writeobject: serialization, writing the object into JSON data;
Readobject: deserialization. It reads object data from JSON data.
To complete today's instance, we need to define a class as a test. Here I will give you a simple employee class with three attributes: name, contact number, and description. The definition is as follows.
Public class employee {// <summary> // employee name // </Summary> Public string name {Get; set ;} /// <summary> /// contact your mobile phone /// </Summary> Public String phone {Get; set ;} /// <summary> /// overview /// </Summary> Public String description {Get; Set ;}}
For the UI, refer to the following XAML. I will not elaborate on it, but you will understand it.
<Page X: class = "app1.mainpage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns: Local = "using: app1" xmlns: D = "http://schemas.microsoft.com/expression/blend/2008" xmlns: MC = "http://schemas.openxmlformats.org/markup-compatibility/2006" MC: ignorable = "D"> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <grid. columndefinitions> <columndefinition/> </grid. columndefinitions> <stackpanel orientation = "vertical" grid. column = "0" margin = "17"> <textblock text = "employee name:"/> <textbox X: Name = "txtname" margin = "0, 2, "/> <textblock text =" contact number: "/> <textbox X: Name =" txtphone "margin =, "/> <textblock text =" employee profile: "/> <textbox X: Name =" txtdesc "margin =, 0, 26 "/> <button content =" save data "Click =" onsave "/> </stackpanel> <stackpanel orientation =" vertical "grid. column = "1" margin = "15"> <button content = "load data" Click = "onloaddata"/> <textblock X: name = "tbinfo" textwrapping = "Wrap" margin = ","/> </stackpanel> </GRID> </Page>
To switch to the Code view, refer to the following code:
Using system; using system. collections. generic; using system. io; using system. LINQ; using Windows. foundation; using Windows. foundation. collections; using Windows. UI. XAML; using Windows. UI. XAML. controls; using Windows. UI. XAML. controls. primitives; using Windows. UI. XAML. data; using Windows. UI. XAML. input; using Windows. UI. XAML. media; using Windows. UI. XAML. navigation; // introduce the following namespace using system. runtime. serialization. JS On; using Windows. storage; using Windows. storage. pickers; using Windows. storage. streams; using Windows. UI. popups; namespace app1 {public sealed partial class mainpage: Page {public mainpage () {This. initializecomponent ();} private async void onloaddata (Object sender, routedeventargs e) {fileopenpicker picker = new fileopenpicker (); picker. commitbuttontext = "open"; picker. filetypefilter. add (". JSON "); Picker. suggestedstartlocation = pickerlocationid. desktop; storagefile datafile = await picker. picksinglefileasync (); If (datafile! = NULL) {// start reading the file using (VAR stream = await datafile. opensequentialreadasync () {// deserialize datacontractjsonserializer SZ = new datacontractjsonserializer (typeof (employee); employee EMP = (employee) SZ. readobject (stream. asstreamforread (); this. tbinfo. TEXT = string. format ("employee name: {0} \ n contact number: {1} \ n Description: {2}", EMP. name, EMP. phone, EMP. description) ;}} private async void onsave (Object sender, routedeventa RGS e) {If (string.isnullorwhitespace(this.txt name. text) | string.isnullorwhitespace(this.txt phone. text) | string.isnullorwhitespace(this.txt DESC. text) return; // select the file storage location filesavepicker picker = new filesavepicker (); picker. commitbuttontext = "save"; picker. suggestedstartlocation = pickerlocationid. desktop; picker. filetypechoices. add ("JSON data file", new string [] {". JSON "}); storagefile DATA = awa It picker. picksavefileasync (); If (Data! = NULL) {using (VAR stream = await data. openasync (fileaccessmode. readwrite) {// create a new object: employee EMP = new employee {name = this.txt name. text, phone = this.txt phone. text, description = this.txt DESC. text}; // start to serialize datacontractjsonserializer srz = new datacontractjsonserializer (EMP. getType (); srz. writeobject (stream. asstreamforwrite (), EMP);} This. showmessagebox ("saved successfully. ") ;}} Private async void showmessagebox (string MSG) {messagedialog dialog = new messagedialog (MSG); await dialog. showasync () ;}} public class employee {/// <summary> /// employee name /// </Summary> Public string name {Get; set ;} /// <summary> /// contact your mobile phone /// </Summary> Public String phone {Get; set ;} /// <summary> /// overview /// </Summary> Public String description {Get; Set ;}}}
It's that simple. Press F5 to run. Enter the corresponding content on the left side of the page and save it.
Open the saved file in notepad and you will see the following:
Return to the application and load the saved JSON file on the right of the page, as shown in:
So far, the JSON serialization and deserialization work has basically been completed. However, there is another problem. Let's continue to discuss it. Just now we can use NotePad to view the saved JSON data, the field name of the JSON object is the same as the attribute name of the class, so sometimes we do not want this. For example, in a class, the attribute name is name, but in JSON data, I want it to be emp_name. Can it be implemented? The answer is yes.
At this time, we only need to change the definition of the employee class.
[System. runtime. serialization. datacontract] public class employee {// <summary> // employee name /// </Summary> [system. runtime. serialization. datamember (name = "emp_name")] public string name {Get; Set ;}/// <summary> /// contact your mobile phone /// </Summary> [system. runtime. serialization. datamember (name = "emp_phoneno")] Public String phone {Get; Set ;}/// <summary> /// overview /// </Summary> [system. runtime. serialization. datamember (name = "emp_desc")] Public String description {Get; set ;}}
As a result, the stored JSON data is shown in: