Asp.net 将数据库里的记录转换成json

http://tech.ddvip.com   2007年11月24日    社区交流

内容摘要:在前面我已经写了asp的版本,最近一个项目中正好需要用json来填充下拉框,所以写了一个asp.net的将数据库里的记录转换成json。

  在前面我已经写了asp的版本,最近一个项目中正好需要用json来填充下拉框,所以写了一个asp.net的将数据库里的记录转换成json,代码如下:

以下是引用片段:
usingSystem;
  usingSystem.Collections.Generic;
  usingSystem.Text;
  usingSystem.Data;
  usingSystem.Data.SqlClient;
  namespaceOTC.Utility
  ...{
  publicsealedclassJSONHelper
  ...{
  /**//// 
  ///获取JSON字符串
  /// 
  ///值
  ///数据表名
  /// 
  publicstaticstringGetJSON(SqlDataReaderdrValue,stringstrTableName)
  ...{
  StringBuildersb=newStringBuilder();
  sb.AppendLine("{");
  sb.AppendLine(""+strTableName+":{");
  sb.AppendLine("records:[");
  try
  ...{
  while(drValue.Read())
  ...{
  sb.Append("{");
  for(inti=0;i<drValue.FieldCount;i++)
  ...{
  sb.AppendFormat(""{0}":"{1}",",drValue.GetName(i),drValue.GetValue(i));
  }
  sb.Remove(sb.ToString().LastIndexOf(’,’),1);
  sb.AppendLine("},");
  }
  sb.Remove(sb.ToString().LastIndexOf(’,’),1);
  }
  catch(Exceptionex)
  ...{
  thrownewException(ex.Message);
  }
  finally
  ...{
  drValue.Close();
  }
  sb.AppendLine("]");
  sb.AppendLine("}");
  sb.AppendLine("};");
  returnsb.ToString();
  }
  }
  }

  接下来你只需要传一个SqlDataReader对象就可以了。

  相关教程:

  PHP V5.2中的新增功能之使用新的JSON扩展

  http://tech.ddvip.com/2007-08/118771525832600.html

  用PHP将XML转换成JSON

  http://tech.ddvip.com/2007-08/118771584632603.html

  基于JSON的高级AJAX开发技术

  http://tech.ddvip.com/2006-11/116396420311155.html

  使用 Google Web Toolkit 和 JSON开发Ajax应用程序

  http://tech.ddvip.com/2007-08/118798387832972.html

来源:中国自学编程网    责编:豆豆技术应用

正在加载评论...