关于DataTable序列化的事儿
Posted 吃饭睡觉敲代码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于DataTable序列化的事儿相关的知识,希望对你有一定的参考价值。
今天写了一个小demo,从数据库中读取到了dataTable,想序列化成json字符串,然后传到前端,进行页面展示,其实很简单的一个步骤,谁知道它出错了!!!
出错的原因是:序列化类型为XX的对象时检测到循环引用,然后百度了一下,有好多解决方案,我没有一一去试,写这个主要记录一下我找到的解决的办法。
链接:http://xuzhihong1987.blog.163.com/blog/static/26731587201101913722238/
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Web.Script.Serialization; namespace Common { public class ConventDataTableToJson { /// <summary> /// 序列化方法(带分页) /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string Serialize(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> result = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc].ToString()); } list.Add(result); } int count = 0; try { count = Convert.ToInt32(dt.TableName); } catch (System.Exception ex) { count = dt.Rows.Count; } string strReturn = ""; if (count == 0) { strReturn = "{\"totalCount\":0,\"data\":[]}"; } else { strReturn = ConventToJson(list, count); } return strReturn; } /// <summary> /// 转换为JSON对象 /// </summary> /// <returns></returns> public static string ConventToJson<T>(List<T> list, int count) { javascriptSerializer serializer = new JavaScriptSerializer(); string strJson = serializer.Serialize(list); strJson = strJson.Substring(1); strJson = strJson.Insert(0, "{totalCount:" + count + ",data:["); strJson += "}"; return strJson; } /// <summary> /// 不需要分页 /// </summary> /// <param name="dt"></param> /// <param name="flag">false</param> /// <returns></returns> public static string Serialize(DataTable dt, bool flag) { JavaScriptSerializer serializer = new JavaScriptSerializer(); List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> result = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc].ToString()); } list.Add(result); } return serializer.Serialize(list); ; } } }
以上是关于关于DataTable序列化的事儿的主要内容,如果未能解决你的问题,请参考以下文章