日期:2011-08-02  浏览次数:20476 次

  在这一两年内数据存储以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