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的 其它版本没有试 暂时还未找到原因!

  • 相关阅读:
    随笔
    转:windows 下 netsh 实现 端口映射(端口转发)
    2015年01月01日:新年第一天:happy new year to myself
    谨记一次问题排查经历
    新机器,分区为NTFS, 安装 Windows XP、Windows Server 2003 时蓝屏问题,修改为 FAT32 即可
    Oracle 11g 的bug?: aix 上,expdp 11.2.0.1 导出,impdp 11.2.0.3 导入,Interval 分区的 【Interval】 分区属性成了【N】
    Cursor for loop in Oracle
    Oracle date 详解
    oracle中to_timestamp和to_date什么区别
    Oracle FM FM09999999 确保8位数字 即使全是0
  • 原文地址:https://www.cnblogs.com/lczblog/p/3310240.html
Copyright © 2011-2022 走看看