zoukankan      html  css  js  c++  java
  • C# DataTable 对象转换成Json时 出现 序列化类型为“System.Reflection.Module”的对象时检测到循环引用 的错误!

    解决办法 :

     Description: DataTable转换JSON对象

    *

    */

     

        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); ;

            }

    }

     原理非常简单,主要思想就是利用Dictionary<string, object>字典,将DataRow属性名/值存储在List<Dictionary<string, object>>中,这样List<T>是能被正常序列化的。

    以上转自:飞天心宏的博客 http://xuzhihong1987.blog.163.com/blog/static/26731587201101913722238/

    另一种比较普通的方法:

    public static string CreateJsonParameters(DataTable dt)
            {
                
    /**//**/
                
    /**//* /****************************************************************************
              * Without goingin to the depth of the functioning of this Method, i will try to give an overview
              * As soon as this method gets a DataTable it starts to convert it into JSON String,
              * it takes each row and in each row it grabs the cell name and its data.
              * This kind of JSON is very usefull when developer have to have Column name of the .
              * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
              * NOTE: One negative point. by this method user will not be able to call any cell by its index.
             * ************************************************************************
    */
                StringBuilder JsonString 
    = new StringBuilder();
                
    //Exception Handling        
                if (dt != null && dt.Rows.Count > 0)
                {
                    JsonString.Append(
    "");
                    JsonString.Append(
    ""T_blog":[ ");
                    
    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        JsonString.Append(
    "");
                        
    for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            
    if (j < dt.Columns.Count - 1)
                            {
                                JsonString.Append(
    """ + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + "",");
                            }
                            
    else if (j == dt.Columns.Count - 1)
                            {
                                JsonString.Append(
    """ + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + """);
                            }
                        }
                        
    /**//**/
                        
    /**//*end Of String*/
                        
    if (i == dt.Rows.Count - 1)
                        {
                            JsonString.Append(
    "");
                        }
                        
    else
                        {
                            JsonString.Append(
    "}, ");
                        }
                    }
                    JsonString.Append(
    "]}");
                    
    return JsonString.ToString();
                }
                
    else
                {
                    
    return null;
                }
            }

    效果是完全相同的。

    页面前段把使用js解析json

      function strToJson(str) {
                var json = eval('(' + str + ')');
                return json;
            }

    但是不知道为什么 使用jquery的 $.parseJSON()方法解析总是出错 jquery的版本是4.1和9.1的 其它版本没有试 暂时还未找到原因!

  • 相关阅读:
    Atitit attilax要工作研究的要素 纪要 方案 趋势 方向 概念 理论
    Atitit 常见每日流程日程日常工作.docx v7 r8f
    Atitit it 互联网 软件牛人的博客列表
    Atitit 信息链(Information Chain)的概念理解 attilax总结
    Atitit 知识点的体系化 框架与方法 如何了解 看待xxx
    Atitit 聚合搜索多个微博 attilax总结
    Atitit 企业知识管理PKM与PIM
    Atitit 项目沟通管理 Atitit 沟通之道 attilax著.docx
    Atitit 项目管理软件 在线服务 attilax总结 1. 项目管理协作的历史 1 1.1. Worktile 406k 1 1.2. Teambition  584k in baidu
    Atitit.每周末总结 于每周一计划日程表 流程表 v8 import 上周遗漏日志补充 检查话费 检查流量情况 Crm问候 Crm表total and 问候
  • 原文地址:https://www.cnblogs.com/lczblog/p/3310240.html
Copyright © 2011-2022 走看看