当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
数据库里的记录与json之间的转换
发布时间:2010/7/2 16:27:47 来源:城市学习网 编辑:ziteng
  数据库里的记录与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对象就可以了。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved