新时尚Windows8开发(33):Json数据处理(B)

来源:互联网 发布:华为数据银行 编辑:程序博客网 时间:2024/05/15 02:06

上一节我们讨论了如何手动方式来处理JSON对象数据,可能你也发现了,是有些痛苦,那么,用什么方法来读写JSON数据才算好玩?有的,如果你耍过WCF,或许已经想到了——JSON序列化和反序列化。

DataContractJsonSerializer类位于System.Runtime.Serialization.Json命名空间,我们只需要简单的调用两个方法就可以完成序列化和反序列化。

WriteObject:序列化,把对象写入JSON数据;

ReadObject:反序列化,从JSON数据中读入对象数据。

 

要完成今天的实例,我们先要定义一个类作为测试,这里我就举一个简单的,员工类,它有三个属性:姓名,联系电话,简介。定义如下。

[csharp] view plaincopyprint?
  1. public class Employee  
  2. {  
  3.     /// <summary>  
  4.     /// 员工姓名  
  5.     /// </summary>  
  6.     public string Name { getset; }  
  7.     /// <summary>  
  8.     /// 联系手机  
  9.     /// </summary>  
  10.     public string Phone { getset; }  
  11.     /// <summary>  
  12.     /// 简介  
  13.     /// </summary>  
  14.     public string Description { getset; }  
  15. }  


对于UI,可以参考下面的XAML,我就不详细说,你会看得懂的。

[html] view plaincopyprint?
  1. <Page  
  2.     x:Class="App1.MainPage"  
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5.     xmlns:local="using:App1"  
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  8.     mc:Ignorable="d">  
  9.   
  10.     <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">  
  11.         <Grid.ColumnDefinitions>  
  12.             <ColumnDefinition/>  
  13.             <ColumnDefinition/>  
  14.         </Grid.ColumnDefinitions>  
  15.         <StackPanel Orientation="Vertical" Grid.Column="0" Margin="17">  
  16.             <TextBlock Text="员工姓名:"/>  
  17.             <TextBox x:Name="txtName" Margin="0,2,0,14"/>  
  18.             <TextBlock Text="联系电话:"/>  
  19.             <TextBox x:Name="txtPhone" Margin="0,2,0,15"/>  
  20.             <TextBlock Text="员工简介:"/>  
  21.             <TextBox x:Name="txtDesc" Margin="0,2,0,26"/>  
  22.             <Button Content="保存数据" Click="onSave"/>  
  23.         </StackPanel>  
  24.         <StackPanel Orientation="Vertical" Grid.Column="1" Margin="15">  
  25.             <Button Content="加载数据" Click="onLoadData"/>  
  26.             <TextBlock x:Name="tbInfo" TextWrapping="Wrap" Margin="0,15,0,0"/>  
  27.         </StackPanel>  
  28.     </Grid>  
  29. </Page>  


切换到代码视图,参考下面代码:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using Windows.Foundation;  
  6. using Windows.Foundation.Collections;  
  7. using Windows.UI.Xaml;  
  8. using Windows.UI.Xaml.Controls;  
  9. using Windows.UI.Xaml.Controls.Primitives;  
  10. using Windows.UI.Xaml.Data;  
  11. using Windows.UI.Xaml.Input;  
  12. using Windows.UI.Xaml.Media;  
  13. using Windows.UI.Xaml.Navigation;  
  14. // 引入以下命名空间  
  15. using System.Runtime.Serialization.Json;  
  16. using Windows.Storage;  
  17. using Windows.Storage.Pickers;  
  18. using Windows.Storage.Streams;  
  19. using Windows.UI.Popups;  
  20.   
  21. namespace App1  
  22. {  
  23.     public sealed partial class MainPage : Page  
  24.     {  
  25.         public MainPage()  
  26.         {  
  27.             this.InitializeComponent();  
  28.         }  
  29.   
  30.   
  31.         private async void onLoadData(object sender, RoutedEventArgs e)  
  32.         {  
  33.             FileOpenPicker picker = new FileOpenPicker();  
  34.             picker.CommitButtonText = "打开";  
  35.             picker.FileTypeFilter.Add(".json");  
  36.             picker.SuggestedStartLocation = PickerLocationId.Desktop;  
  37.             StorageFile dataFile = await picker.PickSingleFileAsync();  
  38.             if (dataFile != null)  
  39.             {  
  40.                 // 开始读取文件  
  41.                 using (var stream = await dataFile.OpenSequentialReadAsync())  
  42.                 {  
  43.                     // 反序列化  
  44.                     DataContractJsonSerializer sz = new DataContractJsonSerializer(typeof(Employee));  
  45.                     Employee emp = (Employee)sz.ReadObject(stream.AsStreamForRead());  
  46.                     this.tbInfo.Text = string.Format("员工姓名:{0}\n联系电话:{1}\n简介:{2}", emp.Name, emp.Phone, emp.Description);  
  47.                 }  
  48.             }  
  49.         }  
  50.   
  51.         private async void onSave(object sender, RoutedEventArgs e)  
  52.         {  
  53.             if (string.IsNullOrWhiteSpace(this.txtName.Text) || string.IsNullOrWhiteSpace(this.txtPhone.Text) || string.IsNullOrWhiteSpace(this.txtDesc.Text))  
  54.                 return;  
  55.             // 选择文件保存位置  
  56.             FileSavePicker picker = new FileSavePicker();  
  57.             picker.CommitButtonText = "保存";  
  58.             picker.SuggestedStartLocation = PickerLocationId.Desktop;  
  59.             picker.FileTypeChoices.Add("JSON数据文件"new string[] { ".json" });  
  60.             StorageFile data = await picker.PickSaveFileAsync();  
  61.             if (data != null)  
  62.             {  
  63.                 using (var stream = await data.OpenAsync(FileAccessMode.ReadWrite))  
  64.                 {  
  65.                     // 创建新对象  
  66.                     Employee emp = new Employee { Name = this.txtName.Text, Phone = this.txtPhone.Text, Description = this.txtDesc.Text };  
  67.                     // 开始序列化  
  68.                     DataContractJsonSerializer srz = new DataContractJsonSerializer(emp.GetType());  
  69.                     srz.WriteObject(stream.AsStreamForWrite(), emp);  
  70.                 }  
  71.                 this.ShowMessageBox("保存成功。");  
  72.             }  
  73.         }  
  74.   
  75.         private async void ShowMessageBox(string msg)  
  76.         {  
  77.             MessageDialog dialog = new MessageDialog(msg);  
  78.             await dialog.ShowAsync();  
  79.         }  
  80.     }  
  81.   
  82.   
  83.     public class Employee  
  84.     {  
  85.         /// <summary>  
  86.         /// 员工姓名  
  87.         /// </summary>  
  88.         public string Name { getset; }  
  89.         /// <summary>  
  90.         /// 联系手机  
  91.         /// </summary>  
  92.         public string Phone { getset; }  
  93.         /// <summary>  
  94.         /// 简介  
  95.         /// </summary>  
  96.         public string Description { getset; }  
  97.     }  
  98. }  


就是这么简单,按下F5运行。在页面左边输入相应内容,保存。

 

用记事本打开刚才保存的文件,你会看到以下内容:

 

回到应用程序,在页面右边,加载刚才保存的JSON,如下图所示:

 

 

到此为止,基本上完成了JSON序列化和反序列的工作了,但是,还有一个问题,我们继续讨论一下,刚才我们用记事本查看保存的JSON数据已经看到,JSON对象的字段名和类的属性名是一样的,那么,有些时候,我们并不希望这样。如:在类中姓名的属性名是Name,但在JSON数据中我希望它是emp_name。可以实现吗?答案是肯定的。

这时候,我们只需把Employee类的定义改一下就可以了。

[csharp] view plaincopyprint?
  1. [System.Runtime.Serialization.DataContract]  
  2. public class Employee  
  3. {  
  4.     /// <summary>  
  5.     /// 员工姓名  
  6.     /// </summary>  
  7.     [System.Runtime.Serialization.DataMember(Name = "emp_name")]  
  8.     public string Name { getset; }  
  9.     /// <summary>  
  10.     /// 联系手机  
  11.     /// </summary>  
  12.     [System.Runtime.Serialization.DataMember(Name = "emp_phoneno")]  
  13.     public string Phone { getset; }  
  14.     /// <summary>  
  15.     /// 简介  
  16.     /// </summary>  
  17.     [System.Runtime.Serialization.DataMember(Name = "emp_desc")]  
  18.     public string Description { getset; }  
  19. }  


如此一来,所保存的JSON数据就如下图所示:

 

转载:http://blog.csdn.net/tcjiaan/article/details/8191186

原创粉丝点击