計(jì)算機(jī)軟考程序員:ASP.NET將數(shù)據(jù)庫里的記錄轉(zhuǎn)換成json
時(shí)間:2008-09-20 00:40:00 來源:無憂考網(wǎng) [字體:小 中 大]
ASP的版本,考試大一個(gè)項(xiàng)目中正好需要用json來填充下拉框,所以寫了一個(gè)asp.net將數(shù)據(jù)庫里的記錄轉(zhuǎn)換成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字符串
///
/// 值
/// 數(shù)據(jù)表名
///
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();
}
}
}
接下來你只需要傳一個(gè)SqlDataReader對象就可以了。
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace OTC.Utility
...{
public sealed class JSONHelper
...{
/**////
/// 獲取JSON字符串
///
/// 值
/// 數(shù)據(jù)表名
///
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();
}
}
}
接下來你只需要傳一個(gè)SqlDataReader對象就可以了。
- 環(huán)球網(wǎng)校:2024年計(jì)算機(jī)軟考高級(jí)旗艦班系規(guī)旗艦班課程
- 計(jì)算機(jī)軟考中級(jí)考幾科?環(huán)球軟考中級(jí)模塊全程班課程推薦!
- 計(jì)算機(jī)軟考中級(jí)證書含金量 環(huán)球網(wǎng)校2025年軟考中級(jí)模塊精講班課程
- 2024年11月計(jì)算機(jī)軟考合格標(biāo)準(zhǔn)(已公布)
- 2024年11月北京計(jì)算機(jī)軟考合格標(biāo)準(zhǔn)(已公布)
- 2024年11月天津計(jì)算機(jī)軟考合格標(biāo)準(zhǔn)(已公布)
- 查看計(jì)算機(jī)軟件水平考試全部文檔 >>