题外话:今天网上翻了翻,查了查,说句实话,不是太深奥了,就是看不懂,今天我用一个简单的,希望能给大家带去帮助,本人知识水平有限,如若有错,请指出,谢谢!
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Documents; 8 using System.Windows.Input; 9 using System.Windows.Media; 10 using System.Windows.Media.Animation; 11 using System.Windows.Shapes; 12 using Microsoft.Phone.Controls; 13 using System.Runtime.Serialization.Json; 14 using System.IO; 15 using System.Text; 16 17 namespace WindowsphoneJson的处理 18 { 19 public partial class MainPage : PhoneApplicationPage 20 { 21 // 构造函数 22 public MainPage() 23 { 24 InitializeComponent(); 25 GetData(); //调用下面获得数据的方法. 26 } 27 //这是一个待处理的JSON格式的字符串. 28 string teststr="[{\"Name\":\"小明\",\"Age\":18},{\"Name\":\"小红\",\"Age\":17}]"; 29 //通过上面的字符串,我们可以知道,这是一个人的集合,所有我们可以创建出一个人的类来,来装载这些数据. 30 public void GetData() 31 { 32 //创建出这个对象来,因为我们分析得出,这样的格式就是一个人的集合. 33 List<Person> list=new List<Person>(); 34 //把字符串编码为字节数组,装进内存流. 35 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(teststr)); 36 //通过list,获得类型,创建出序列化JSON的对象. 37 DataContractJsonSerializer ser = new DataContractJsonSerializer(list.GetType()); 38 //用序列化json格式的对象把内存流的字节数组反序列化为对象.并强转为对象的类型,然后赋值给上面准备后的List<Person>的对象list. 39 list=( List<Person>)ser.ReadObject(ms); 40 //到这里,我们的反序列化就完成了.下面是验证的过程. 41 ms.Close(); //把流关闭. 42 foreach (Person item in list) 43 { 44 txtshow.Text += item.Name + item.Age + "\r\n"; 45 } 46 } 47 } 48 49 public class Person //这个就是我们创建的人类 50 { 51 public string Name { get; set; } //人的名字.因为在json字符串里有这样的键. 52 public int Age { get; set; } //人的年龄.因为在json字符串里有这样的键. 53 } 54 }
下面是效果图

注意:使用DataContractJsonSerializer,需要引用程序集System.ServiceModel.Web,还要引用命名空间:using System.Runtime.Serialization.Json;
该注释,我都已经在代码中注释好了,很多时候,不要一开始就研究很复杂的,一切都要从简单入手.希望这篇文给新手们带去帮助!
浙公网安备 33010602011771号