計算機軟考程序員:ASP.NET將數據庫裡的記錄轉換成json

計算機軟考程序員:ASP.NET將數據庫裡的記錄轉換成json,第1張

計算機軟考程序員:ASP.NET將數據庫裡的記錄轉換成json,第2張

ASP的版本,考試大一個項目中正好需要用json來填充下拉框,所以寫了一個asp.net將數據庫裡的記錄轉換成json,代碼如下:
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Data;
  using System.Data.SqlClient;
  namespace OTC.Utility
  ...{
  public sealed class JSONHelper
  ...{
  ///
  /// 獲取JSON字符串
  ///
  /// 值
  /// 數據表名
  ///
  public static string GetJSON(SqlDataReader drValue, string strTableName)
  ...{
  StringBuilder sb = new StringBuilder();
  sb.AppendLine("{");
  sb.AppendLine("" strTableName ":{");
  sb.AppendLine(" records:[");
 try
  ...{
  while (drValue.Read())
  ...{
  sb.Append(" {");
  for (int i = 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(Exception ex)
  ...{
  throw new Exception(ex.Message);
  }
  finally
  ...{
  drValue.Close();
  }
  sb.AppendLine(" ]");
  sb.AppendLine(" }");
  sb.AppendLine(" };");
  return sb.ToString();
  }
  }
  }
  接下來你衹需要傳一個SqlDataReader對象就可以了。

位律師廻複

生活常識_百科知識_各類知識大全»計算機軟考程序員:ASP.NET將數據庫裡的記錄轉換成json

0條評論

    發表評論

    提供最優質的資源集郃

    立即查看了解詳情