Created
August 27, 2017 21:29
-
-
Save richardschoen/77b9e121fdb02dada1ccb9ac1cd5f21d to your computer and use it in GitHub Desktop.
DataTable Object to JSON Object using String Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string DataTableToJsonObj(DataTable dt) | |
{ | |
DataSet ds = new DataSet(); | |
ds.Merge(dt); | |
StringBuilder JsonString = new StringBuilder(); | |
if (ds != null && ds.Tables[0].Rows.Count > 0) | |
{ | |
JsonString.Append("["); | |
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) | |
{ | |
JsonString.Append("{"); | |
for (int j = 0; j < ds.Tables[0].Columns.Count; j++) | |
{ | |
if (j < ds.Tables[0].Columns.Count - 1) | |
{ | |
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\","); | |
} | |
else if (j == ds.Tables[0].Columns.Count - 1) | |
{ | |
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\""); | |
} | |
} | |
if (i == ds.Tables[0].Rows.Count - 1) | |
{ | |
JsonString.Append("}"); | |
} | |
else | |
{ | |
JsonString.Append("},"); | |
} | |
} | |
JsonString.Append("]"); | |
return JsonString.ToString(); | |
} | |
else | |
{ | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment