Json字符串對於做web應用的應該很熟悉,其實在很多請求我們返回的都是Json字符串。那對於C#代碼如何處理Json字符串呢,.Net封裝了一個類叫做JavaScriptSerializer[MSDN Library 鏈接http://msdn.microsoft.com/en-us/library/ee191864(v=vs.110).aspx];這個類提供了一個方法。
下面這個是我在快遞100往抓取的一個圓通的快遞信息。對於我們有用的信息是快遞時間,快遞狀況。那我該如何來做。
{"message":"ok","nu":"9356359685","ischeck":"1","com":"yuantong","status":"200","condition":"F00","state":"3","data":[{"time":"2014-09-01 21:19:06","context":"甘肅省武威市公司 已簽收 ","ftime":"2014-09-01 21:19:06"},{"time":"2014-09-01 09:09:28","context":"甘肅省武威市公司 派件中 ","ftime":"2014-09-01 09:09:28"},{"time":"2014-09-01 09:06:27","context":"甘肅省武威市公司 已收入 ","ftime":"2014-09-01 09:06:27"},{"time":"2014-08-31 19:53:47","context":"甘肅省蘭州市公司 已發出 ","ftime":"2014-08-31 19:53:47"},{"time":"2014-08-31 19:17:41","context":"甘肅省蘭州市公司 已收入 ","ftime":"2014-08-31 19:17:41"},{"time":"2014-08-28 23:44:26","context":"廣東省深圳市橫崗公司 已打包 ","ftime":"2014-08-28 23:44:26"},{"time":"2014-08-28 23:19:12","context":"廣東省深圳市橫崗公司 已收件 ","ftime":"2014-08-28 23:19:12"},{"time":"2014-08-28 21:55:35","context":"廣東省深圳市橫崗公司 已收件 ","ftime":"2014-08-28 21:55:35"}]}
1. 首先分析Json字符串結構. Json{ message,nu,isCheck,Data{time,context,ftime}};我們先定義一個類,取名為PostalDeliveryModel,類名的結構需要與Json結構對應,名稱需要保持一樣[忽略大小寫],其次對應的字段說會自動轉換類型的,類型如果不符合會拋出異常
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestJson { public class PostalDeliveryModel { private string message = string.Empty; private string nu = string.Empty; private List<SingalData> data = new List<SingalData>(); // Puclic的名字需要與Json字符串相同,但是忽略大小寫 public string Message { get { return this.message; } set { this.message = value; } } public string Nu { get { return this.nu; } set { this.nu = value; } } public List<SingalData> Data { get { return this.data; } set { this.data = value; } } } public class SingalData { private DateTime time = System.DateTime.Now; private string context = string.Empty; private DateTime ftime = System.DateTime.Now; public DateTime Time { get { return this.time; } set { this.time = value; } } public DateTime FTime { get { return this.ftime; } set { this.ftime = value; } } public string Context { get { return this.context; } set { this.context = value; } } } }
2.對象什么好后只需要調用方法即可:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Web.Script.Serialization; // 此命名空間對應的框架是 System.Web.Extensions namespace TestJson { public class Program { public static void Main(string[] args) { string jsonStr = new StreamReader("JsonData.txt").ReadToEnd(); PostalDeliveryModel mode = new JavaScriptSerializer().Deserialize<PostalDeliveryModel>(jsonStr); Console.ReadKey(); } } }
3.運行監控model對象.數據已經在對象里面了。
4.方法回顧,雖然獲取到了。不過這種方法類的Public屬性名稱必須與Json字符串對應,不知道可否通過在Public屬性的上面加上[標簽]來映射,這樣可以自定義名稱,不再需要與Json里面名稱一樣。求其他大牛在評論的時候指點一下。