数据库里的记录与json之间如何转换

数据库里的记录与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对象就可以了。
到这里数据库里的记录与json之间的转换就可以实现了,通过上文中的代码,数据库里的记录与json之间的转换就容易很多了,二者之间的转换的介绍主要是以代码的形式展现在大家面前,对于没有很多数据库知识的初学者来说可能比较不容易理解,希望大家能够深入其中去学习。

【编辑推荐】

  1. 详解Oracle数据库备份不同的恢复特性
  2. Access数据库成功导入Oracle库方法
  3. Oracle数据库中使用外部表的心得
THE END