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();
}
}
}
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中的数据转换为JSON格式字符串的方法。该方法通过遍历读取器中的每一行,并将其字段名及对应的值组合成JSON格式。适用于需要将数据库查询结果快速转化为JSON格式的应用场景。
1872

被折叠的 条评论
为什么被折叠?



