怎么把Json字符串转换成DataRow

2024-12-29 06:25:59
推荐回答(1个)
回答1:

可以考虑把dataset或则datatable转成json,如把 datatable的数据转成json:
///


/// Datatable转换为Json
///

/// Datatable对象
/// Json字符串
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();

if (dt.Rows.Count == 0)
{
jsonString.Append("[{}]");
return jsonString.ToString();
}

jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}