天天看点

将数据表转化为json

  • 很多时候不同的客户端需要通过json通信,这里就是一个将从数据库查询到的列表转化为json格式的方法
private string GetDatasetToJson(DataSet ds)
        {
            if (ds == null || ds.Tables.Count <=  || ds.Tables[].Rows.Count <= )
            {
                //如果查询到的数据为空则返回标记ok:false
                return "{\"ok\":false}";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"ok\":true,");
            foreach (DataTable dt in ds.Tables)
            {
                sb.Append(string.Format("\"{0}\":[", dt.TableName));
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    for (int i = ; i < dr.Table.Columns.Count; i++)
                    {
                        sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\\"").Replace("\'", "\\\'"), ObjToStr(dr[i]).Replace("\"", "\\\"").Replace("\'", "\\\'")).Replace(Convert.ToString((char)), "\\r\\n").Replace(Convert.ToString((char)), "\\r\\n");
                    }
                    sb.Remove(sb.ToString().LastIndexOf(','), );
                    sb.Append("},");
                }
                sb.Remove(sb.ToString().LastIndexOf(','), );
                sb.Append("],");
            }
            sb.Remove(sb.ToString().LastIndexOf(','), );
            sb.Append("}");
            return sb.ToString();
        }
           
  • 使用此方法
/// <summary>
        /// 获取群列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GroupToOpenfire(string username)
        {
            string jString = "";
            if (username != null)
            {
                jString = GetDatasetToJson(DB.GetDataSet(EnringContext.Current.Config.ConnectionStrings.Server, CommandType.Text, string.Format("select ofMucRoom.name from ofMucRoom where ofMucRoom.roomID in(select ofMucMember.roomID from ofMucMember where jid='{0}')", username)));

            }
            return Content(jString);
        }

        /// <summary>
        /// 获取群内成员列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GroupMemberToOpenfire(string groupname)
        {
            string jString = "";
            if (groupname != null)
            {
                jString = GetDatasetToJson(DB.GetDataSet(EnringContext.Current.Config.ConnectionStrings.Server, CommandType.Text, string.Format("select ofMucMember.jid from ofMucMember where ofMucMember.roomID in(select ofMucRoom.roomID from ofMucRoom where name='{0}')", groupname)));

            }
            return Content(jString);
        }
           
  • 数据库查出的数据截图
将数据表转化为json