从 Web 服务返回数据时怎么样?以下是适合 .Net 2.0 的两种方法,它们采用 DataTable 或 DataRow 参数,并返回要从 Web 服务发送到客户端的 JSON 格式字符串:
public string GetJson(DataRow r)
{
int index = 0;
StringBuilder json = new StringBuilder();
foreach (DataColumn item in r.Table.Columns)
{
json.Append(String.Format("\"{0}\" : \"{1}\"", item.ColumnName, r[item.ColumnName].ToString().Replace("\"","\\\"")));
if (index < r.Table.Columns.Count - 1)
{
json.Append(", ");
}
index++;
}
return "{" + json.ToString() + "}";
}
public string GetJson(DataTable t)
{
int index = 0;
StringBuilder json = new StringBuilder();
foreach (DataRow currRow in t.Rows)
{
json.Append(GetJson(currRow));
if (index < t.Rows.Count - 1)
{
json.Append(", ");
}
}
return "[" + json.ToString() + "]";
}
Run Code Online (Sandbox Code Playgroud)
然后可以发送结果并在客户端上进行评估。
归档时间: |
|
查看次数: |
4809 次 |
最近记录: |