본문 바로가기

[C#] C#에서 DataTable 을 JSON으로 변경

I'm 영서 2022. 4. 7.
반응형

DataTableToJSON

 

MS에서 권장하는 방법은 총 3가지이다.

 

1. StringBuilder 를 사용하는 방법

public string DataTableToJSONWithStringBuilder(DataTable table)   
{  
    var JSONString = new StringBuilder();  
    if (table.Rows.Count > 0)   
    {  
        JSONString.Append("[");  
        for (int i = 0; i < table.Rows.Count; i++)   
        {  
            JSONString.Append("{");  
            for (int j = 0; j < table.Columns.Count; j++)   
            {  
                if (j < table.Columns.Count - 1)   
                {  
                    JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");  
                }   
                else if (j == table.Columns.Count - 1)   
                {  
                    JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");  
                }  
            }  
            if (i == table.Rows.Count - 1)   
            {  
                JSONString.Append("}");  
            }   
            else   
            {  
                JSONString.Append("},");  
            }  
        }  
        JSONString.Append("]");  
    }  
    return JSONString.ToString();  
}

 

2.JavaScriptSerializer를 사용하는 방법

**JavaScriptSerializer를 사용할 수 있도록 import 해줘야한다.

using System.Web.Script.Serialization;  

public string DataTableToJSONWithJavaScriptSerializer(DataTable table) 
{  
    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();  
    List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> ();  
    Dictionary < string, object > childRow;  
    foreach(DataRow row in table.Rows) 
    {  
        childRow = new Dictionary < string, object > ();  
        foreach(DataColumn col in table.Columns) 
        {  
            childRow.Add(col.ColumnName, row[col]);  
        }  
        parentRow.Add(childRow);  
    }  
    return jsSerializer.Serialize(parentRow);  
}

3. Newtonsoft 라이브러리 사용법

**라이브러리를 사용할 수 있도록 import 해줘야한다.

using Newtonsoft.JSON;  
  
public string DataTableToJSONWithJSONNet(DataTable table) {  
   string JSONString=string.Empty;  
   JSONString = JSONConvert.SerializeObject(table);  
   return JSONString;  
}

 

반응형

'Study > C#' 카테고리의 다른 글

[C#] Sealed  (0) 2022.04.12
[C#] C#에서 POST방식으로 특정 URL로 데이터 전송  (0) 2022.04.07
[C#] Oracle 연결해서 써먹기  (0) 2021.04.23
[C#] 파일 입출력  (0) 2021.04.19
[C#] C#에서의 배열  (0) 2021.03.04

댓글