在這一兩年內數據存儲以json格式風靡全球。各個大大小小的網站都會使用json格式來存儲一些細節或只讀(非查詢篩選條件)的信息。而在c#後臺代碼讀取json 格式轉化爲Datatable或者其他對象,json字符串數據提取某些值時都顯得極其繁瑣。
現在我們看看使用最原始的辦法(數組分拆法)提取json字符串數據提取某些值:
示例1:假設我們有一個數據存儲的是網站信息:
string txtRent = @"{'網站名稱':'腦球','網站地址':'http://www.naoqiu.com','IP':'192.168.0.1','綜合排名':'沒有排名數據'},
{'網站名稱':'家常菜譜','網站地址':'http://shipu.naoqiu.com','IP':'192.168.0.2','綜合排名':'12345678'},
{'網站名稱':'公交查詢網','網站地址':'http://bus.naoqiu.com','IP':'192.168.1.2','綜合排名':'12345678'}";
接下來我們得從這些信息中獲取網站地址,數組分拆法代碼如下:
/// <summary>
/// 數組分拆法
/// </summary>
/// <returns></returns>
public static string[] GetRentInfo()
{
string txtRent = @"{'網站名稱':'腦球','網站地址':'http://www.naoqiu.com','IP':'192.168.0.1','綜合排名':'沒有排名數據'},
{'網站名稱':'家常菜譜','網站地址':'http://shipu.naoqiu.com','IP':'192.168.0.2','綜合排名':'12345678'},
{'網站名稱':'公交查詢網','網站地址':'http://bus.naoqiu.com','IP':'192.168.1.2','綜合排名':'12345678'}";
string[] items = txtRent.TrimEnd('}').Split('}');
string[] newItems=new string[items.Length];
int i = 0, index = 0;
string tem;
foreach (string s in items) {
index = s.IndexOf("網站地址");
tem = s.Substring(index + 7);
newItems[i++] = tem.Split('\'')[0];
}
return newItems;
}
這種方法雖然可以實現功能,但似乎代碼寫得有些繁雜,執行效率底,那我們怎麼樣來提高代碼的提高效率,以及簡潔性? 答案是有的,使用正則來獲取相應的數據:
/// <summary>
/// 正則基礎應用
/// </summary>
/// <returns></returns>
public static string[] GetInfo_Domain() {
string txtRent = @"{'網站名稱':'腦球','網站地址':'http://www.naoqiu.com','IP':'192.168.0.1','綜合排名':'沒有排名數據'},
{'網站名稱':'家常菜譜','網站地址':'http://shipu.naoqiu.com','IP':'192.168.0.2','綜合排名':'12345678'},
{'網站名稱':'公交查詢網','網站地址':'http://bus.naoqiu.com','IP':'192.168.1.2','綜合排名':'12345678'}";
MatchCollection matches = Regex.Matches(txtRent, @"(?<=網站地址\'\:\')[^\']+");
string[] newItems=new string[matches.Count];
int i = 0;
foreach (Match m in matches) {
newItems[i++] = m.Value;
}
return newItems;
}
總結:看到這個方法是否覺得正則好方便!正則的應用非常廣泛,比如網頁內容的提取。下個章節講解通過正則自定義完成json與DataTable互轉。
網上的資源及本文參考文獻
- 微軟的正則表達式教程
- System.Text.RegularExpressions.Regex類(MSDN)
- 專業的正則表達式教學網站(英文)
- 關於.Net下的平衡組的詳細討論(英文)
- Mastering Regular Expressions (Second Edition)
- 正則表達式30分入門教程
當然還有微軟的.NET中實現JSON的API
如果你想用net json 的api可以看看這篇文章:http://www.cnblogs.com/litongtong/archive/2008/01/12/1036312.html