星空网 > 软件开发 > 操作系统

Windows 10开发基础——XML和JSON (一)

主要内容:

     JSON的序列化与反序列化

    

 

1.JSON的序列化与反序列化

    JSON(JavaScript Object Notation)是一种轻量级的数据交换语言,它虽然是JavaScript的一个子集,但它是独立于语言的文本格式。它的数据格式比较简单,易于读写,且都是压缩的,占用带宽小且易于解析,通常会用JSON格式来传输数据或者用于数据存储。有关JSON数据结构语法的更多知识大家可以在网上其它的地方进行了解,我们只要记住在服务端向客户端传输数据时经常使用它,然后对它的序列化和反序列化非常值得了解就ok了。序列化的过程就是把实体类对象转化成JSON字符串对象,直接把实体类的属性名称和属性值组成“名称/值”的格式,反序列化过程则正好相反。(本**渣一枚,关于这些比较正式的语言也不太会说,然后有些直接搬的是书上我读得懂的文字咯)

     在这里序列化和反序列化,我们都来学习两种方法,一个是DataContractJsonSerializer(位于System.Runtime.Serialization.Json命名空间下),另一个是JsonObject和JsonArray(位于Windows.Data.Json命名空间下)。下面是具体的演示:

     序列化:

     首先我们定义一个实体类(Student.cs),有Id、Nam、Age三个属性,getTestData()用来返回测试数据。

 1  public class Student 2   { 3     public string Id { get; set; } 4     public string Name { get; set; } 5     public int Age { get; set; } 6  7     public static List<Student> getTestData() 8     { 9       List<Student> studentList = new List<Student>();10       studentList.Add(new Student() { Id = "201313138063", Name = "czhhhh", Age = 18 });11       studentList.Add(new Student() { Id = "201313138033", Name = "xxxxzh", Age =22 });12       studentList.Add(new Student() { Id = "201313138045", Name = "wwwko", Age = 19 });13       studentList.Add(new Student() { Id = "201313138028", Name = "Marrio", Age = 19 });14       studentList.Add(new Student() { Id = "201313138016", Name = "Mike", Age = 20});15       return studentList;16     }17   }

     然后来进行序列化操作:直接看下面的代码吧(方法一或者二注释掉一个),注释写得很详细。(真废话~~)

 1   private void InitData() 2     { 3     4       List<Student> studentlist = Student.getTestData();   //取得测试数据 5  6       //序列化Json 方法一:      7      DataContractJsonSerializer seriliazer = new DataContractJsonSerializer(studentlist.GetType()); 
8 //需要一个Type值,因为我们要序列化的是一个列表数据,直接就拿
//学生列表来studentlist.GetType(),这里我们应该了解typeof 和GetType()的区别 9 10 using (MemoryStream ms=new MemoryStream())11 { 12 seriliazer.WriteObject(ms, studentlist);
//WriteObject:Serializes a specified object to JSON data 13 // and writes the resulting JSON to a stream.(Serializes和writes)14 15 ms.Position = 0; //注意这个是必须的,因为上一步的操作16 //中ms的Position值会指向流的最后,为了后面的读取必须移到开头17 18 using (StreamReader reader=new StreamReader(ms)) //从流中读取数据19 {20 tb.Text = reader.ReadToEnd(); //将读取到的数据进行显示21 }22 }23 24 //序列化Json 方法二:25 JsonArray stujsonarray = new JsonArray();
//我们要序列化的是一个集合数据(List<Student>),所以要借助JsonArray26 //这里JsonArray对应List<Student>,而JsonObject则对应Student27
foreach (var stu in studentlist)28 {29 JsonObject stujson = new JsonObject();30 stujson.SetNamedValue("id", JsonValue.CreateStringValue(stu.Id)); //name-value 键值对31 stujson.SetNamedValue("name", JsonValue.CreateStringValue(stu.Name));32 stujson.SetNamedValue("age", JsonValue.CreateNumberValue(stu.Age));33 stujsonarray.Add(stujson); //将JsonObject对象添加到JsonArray34 }35 tb.Text = stujsonarray.Stringify(); //调用Stringify()返回封装值的 JSON 表示形式进行显示36 }

     看一下序列化后的结果:

          Windows 10开发基础——XML和JSON (一)images/loading.gif' data-original="http://images2015.cnblogs.com/blog/643534/201510/643534-20151031024330669-1053189782.png" width="269" height="271" />Windows 10开发基础——XML和JSON (一)

         

        反序列化:

         我们把上面序列化得到的JSON数据保存到一个文件中(Student.txt),然后copy到项目文件夹下来进行反序列化。      

 1    private async void InitDeData() 2     { 3       //从项目文件夹中读取json到字符串text中 4       StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; 5       StorageFile storagefile = await installFolder.GetFileAsync("student.txt"); 6       string text = await FileIO.ReadTextAsync(storagefile); 7  8       List<Student> stulist = new List<Student>(); 9    10       //反序列化JSON 方法一11      // DataContractJsonSerializer seriliazer = new DataContractJsonSerializer(typeof(List<Student>));12   
//将json字符串转化为byte []来作为参数实例化MemoryStream
// using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text)))
13 // { 14 // stulist = seriliazer.ReadObject(ms) as List<Student>;
// // Reads a document stream in the JSON (JavaScript Object Notation) format15 // // and returns the deserialized object. (read和return)16 // // 强制转换成List<Student>
18 // }19 //listView.ItemsSource = stulist; //绑定到ListView控件上进行展示20 21 //反序列化JSON 方法二 22 JsonArray jsonarray = JsonArray.Parse(text); //将JSON字符串转换成JsonArray
// (因为我们的JSON字符串是由多个对象组成的数据,单个对象用JsonObjcet.Parse)
23 for (int i = 0; i < jsonarray.Count; i++)24 {25 JsonObject jsonobj = jsonarray.GetObjectAt((uint)i);26 27 // 从键值对中取数据28 stulist.Add(new Student() { Id = jsonobj.GetNamedString("Id"),
Name = jsonobj.GetNamedString("Name"),
Age = (int)jsonobj.GetNamedNumber("Age") });29 }30 listView.ItemsSource = stulist;31 }

           来看反序列化后的结果:

           Windows 10开发基础——XML和JSON (一)          

2.

     

      和上面JSON的操作相似,

   序列化:

   首先我们还是得定义一个实体类(Book.cs),getTestData返回测试数据。

 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 = "家", Author = "巴金", Isbn = "9787020058594", Price = 25.00M });      booklist.Add(new Book() { Name = "希尔伯特几何基础", Author = "希尔伯特", Isbn = "9787301148037", Price = 69.00M });      booklist.Add(new Book() { Name = "自然哲学之数学原理", Author = "牛顿", Isbn = "9787301095515", Price = 45.00M });      booklist.Add(new Book() { Name = "卓有成效的管理者", Author = "德鲁克", Isbn = "9787111280712", Price = 55.00M });      booklist.Add(new Book() { Name = "革命年代", Author = "高华", Isbn = "9787218061948", Price = 35.00M });      return booklist;    }  }

      然后来看具体的序列化操作:注意方法二的规律性(先是books,然后在books里面添加book,book里面有各种属性)

 private async void InitData()    {      List<Book> booklist = Book.getTestData();      //  //序列化 方法一: 这个和序列化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();        }      }      //  //序列化 方法二:      //////xdoc.AppendChild(books);      //foreach (var book in booklist)      //{      //  //  //  name.InnerText = book.Name;      //  book1.AppendChild(name);      //  //  author.InnerText = book.Author;      //  book1.AppendChild(author);      //  //  Isbn.InnerText = book.Isbn;      //  book1.AppendChild(Isbn);      //  //  Price.InnerText = book.Price.ToString();      //  book1.AppendChild(Price);      //  books.AppendChild(book1);      //}         //StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("book.                 CreationCollisionOption.ReplaceExisting);      //await xdoc.SaveToFileAsync(file);      //if (file != null)      //{      //  tb.Text = await FileIO.ReadTextAsync(file);      //}    }

       再呢,就是序列化后的结果咯。(我们这里都是内联式的属性,那种key="value"的自行尝试)

       Windows 10开发基础——XML和JSON (一)Windows 10开发基础——XML和JSON (一)

     反序列化:

     上面序列化的过程中我们已经将序列化好的数据保存到了

     方法二看起来代码比较多,其实我们只要掌握了SelectNodes的参数XPath的写法,然后再调试,快速监视一下,根据具体的

       List<Book> booklist = Book.getTestData();      // 序列化 方法一: 这个和序列化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();        }      }      //反序列化      using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(tb.Text)))      {        DataContractSerializer deserializer = new DataContractSerializer(typeof(List<Book>));        ms.Position = 0;//这个不要忘记!!!        booklist = deserializer.ReadObject(ms) as List<Book>;      }      listView.ItemsSource = booklist;


      //反序列化                                xdoc.Load                                foreach (var node in nodelist)
                {
                                        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;

     下面是方法一的运行结果:

Windows 10开发基础——XML和JSON (一)

   

    ok,这个就是

 




原标题:Windows 10开发基础——XML和JSON (一)

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流