출처 : 본인
출처2 : https://msdn.microsoft.com/ko-kr/library/system.web.script.serialization.javascriptserializer(v=vs.90).aspx

우선 참조에 System.Web.Extensions 를 추가한다.

확장메서드로 구현하였기 때문에
DataTable.ToJson();
과 같은 식으로 사용하면 된다.
또는
CommonExtensions.ToJson(DataTable);
과 같이 사용해도 된다.


using System.Collections.Generic;

using System.Data;

 

public static class CommonExtensions

{

    public static string ToJson(this DataTable value)

    {

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

serializer.MaxJsonLength = 2147483647;

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

        Dictionary<string, object> row;

        foreach (DataRow dr in value.Rows)

        {

            row = new Dictionary<string, object>();

            foreach (DataColumn col in value.Columns)

            {

                row.Add(col.ColumnName, dr[col]);

            }

            rows.Add(row);

        }

        return serializer.Serialize(rows);

    }

 

    public static string ToJson(this DataSet value)

    {

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

serializer.MaxJsonLength = 2147483647;

        Dictionary<string, List<Dictionary<string, object>>> dsList = new Dictionary<string, List<Dictionary<string, object>>>();

        List<Dictionary<string, object>> rows;

        Dictionary<string, object> row;

 

        foreach (DataTable dt in value.Tables)

        {

            rows = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)

            {

                row = new Dictionary<string, object>();

                foreach (DataColumn col in dt.Columns)

                {

                    row.Add(col.ColumnName, dr[col]);

                }

                rows.Add(row);

            }

            dsList.Add(dt.TableName, rows);

        }

        return serializer.Serialize(dsList);

    }

}




















Posted by motolies
,