public static string ToJsonArray(this DataTable table, List
{
StringBuilder sb = new StringBuilder();
int rowsAdded = 0;
List
for (int i = 0; i < table.Columns.Count; ++i)
{
// If the calling method has requested to skip any columns, we need to add it to the skipColumns
if ((propertiesToInclude.Count > 0 && !propertiesToInclude.Exists(x => x.Equals(table.Columns[i].ColumnName, StringComparison.InvariantCultureIgnoreCase))) ||
propertiesToExclude.Exists(x => x.Equals(table.Columns[i].ColumnName, StringComparison.InvariantCultureIgnoreCase)))
{
skipColumns.Add(i);
}
}
for (int i = 0; i < table.Rows.Count; i++)
{
sb.Append(rowsAdded > 0 ? ", {" : "{");
int colsAdded = 0;
for (int j = 0; j < table.Columns.Count; j++)
{
if (skipColumns.Contains(j))
{
continue;
}
if (table.Columns[j].DataType == typeof(string))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
sb.Append("\"" + table.Rows[i][j].ToString().ToJsonString() + "\"");
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(int))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
if (table.Rows[i][j] != DBNull.Value)
{
sb.Append(table.Rows[i][j]);
}
else
{
sb.Append("null");
}
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(float))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
if (table.Rows[i][j] != DBNull.Value)
{
sb.Append(table.Rows[i][j]);
}
else
{
sb.Append("null");
}
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(decimal))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
if (table.Rows[i][j] != DBNull.Value)
{
sb.Append(table.Rows[i][j]);
}
else
{
sb.Append("null");
}
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(double))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
if (table.Rows[i][j] != DBNull.Value)
{
sb.Append(table.Rows[i][j]);
}
else
{
sb.Append("null");
}
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(DateTime))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
sb.Append("\"" + table.Rows[i][j] + "\"");
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(bool))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
if (table.Rows[i][j] != DBNull.Value)
{
sb.Append(table.Rows[i][j].ToString().ToLower());
}
else
{
sb.Append("null");
}
colsAdded++;
}
else if (table.Columns[j].DataType == typeof(Guid))
{
sb.Append((colsAdded > 0 ? ", \"" : "\"") + table.Columns[j].ColumnName + "\":");
sb.Append("\"" + table.Rows[i][j] + "\"");
colsAdded++;
}
}
sb.Append("}");
rowsAdded++;
}
return sb.ToString();
}
No comments:
Post a Comment