Datatable 生成json格式
2020-12-13 02:34
标签:style blog class code color c Datatable 生成json格式,搜素材,soscw.com Datatable 生成json格式 标签:style blog class code color c 原文地址:http://www.cnblogs.com/zhang9418hn/p/3718641.html
public
string
GetJsonFromDataTable(DataTable dt,
int
total,
bool
ShowFooter,
string
fields,
string
inputfiled,
string
ShowMessage =
"合计:"
,
string
filter =
""
)
{
StringBuilder stringBuilder =
new
StringBuilder();
if
(dt.Rows.Count == 0)
{
stringBuilder.Append(
"{ "
);
stringBuilder.Append(
"\"rows\":[ "
);
stringBuilder.Append(
"]"
);
stringBuilder.Append(
","
);
stringBuilder.Append(
"\"total\":"
);
stringBuilder.Append(total);
stringBuilder.Append(
",\"footer\":["
);
stringBuilder.Append(
"]"
);
stringBuilder.Append(
"}"
);
return
stringBuilder.ToString();
}
stringBuilder.Append(
"{ "
);
stringBuilder.Append(
"\"rows\":[ "
);
for
(
int
i = 0; i
{
stringBuilder.Append(
"{ "
);
for
(
int
j = 0; j
{
if
(j
{
stringBuilder.Append(
string
.Concat(
new
string
[]
{
"\""
,
dt.Columns[j].ColumnName.ToString().ToLower(),
"\":\""
,
this
.JsonCharFilter(dt.Rows[i][j].ToString()),
"\","
}));
}
else
{
if
(j == dt.Columns.Count - 1)
{
stringBuilder.Append(
string
.Concat(
new
string
[]
{
"\""
,
dt.Columns[j].ColumnName.ToString().ToLower(),
"\":\""
,
this
.JsonCharFilter(dt.Rows[i][j].ToString()),
"\""
}));
}
}
}
if
(i == dt.Rows.Count - 1)
{
stringBuilder.Append(
"} "
);
}
else
{
stringBuilder.Append(
"}, "
);
}
}
stringBuilder.Append(
"]"
);
stringBuilder.Append(
","
);
stringBuilder.Append(
"\"total\":"
);
stringBuilder.Append(total);
if
(ShowFooter && fields.Length > 0 && inputfiled.Length > 0)
{
stringBuilder.Append(
",\"footer\":[{"
);
stringBuilder.Append(
string
.Concat(
new
string
[]
{
"\""
,
inputfiled,
"\":\""
,
ShowMessage,
"\","
}));
string
[] array = fields.Split(
new
char
[]
{
‘,‘
});
for
(
int
k = 0; k
{
if
(k
{
stringBuilder.Append(
string
.Concat(
new
object
[]
{
"\""
,
array[k],
"\":\""
,
dt.Compute(
"sum("
+ array[k] +
")"
, filter),
"\","
}));
}
else
{
stringBuilder.Append(
string
.Concat(
new
object
[]
{
"\""
,
array[k],
"\":\""
,
dt.Compute(
"sum("
+ array[k] +
")"
, filter),
"\""
}));
}
}
stringBuilder.Append(
"}]"
);
}
stringBuilder.Append(
"}"
);
return
stringBuilder.ToString();
}