asp.net 返回json格式

如 {
“result”:1
}
后台代码如何实现?

新建一个 一般处理程序文件 Handler1.ashx
然后在Handler1.ashx.cs 里面写如下代码 public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string json = "[{'user_id':'123'}]";
context.Response.Write(json);
}
前台 用ajax 访问 Handler1.ashx 就可以得到json 数据了
建议 用jquery 的ajax 方法
$.ajax({
type: "POST",
url: "Handler1.ashx",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-01-11
下载 Newtonsoft.Json.dll
在web项目中添加引用
string Json = JsonConvert.SerializeObject(GetData(), new DataTableConverter());
//将datatable转成Json格式返回

这是.net下面处理json最好的类。可以试试
第2个回答  2012-01-11
public static string DataTableToJson(DataTable dt, string JsonName)
{

try
{
if (dt == null)
{
return "DataTable Is Null ,So I Can't Do It To Json!";
}
string josn = "\"" + JsonName + "\":[";

string temp = "";
for (int j = 0; j < dt.Rows.Count; j++)
{

temp = temp + "{";
for (int i = 0; i < dt.Columns.Count; i++)
{
temp += "\"" + dt.Columns[i].ColumnName.ToLower() + "\":\"" + dt.Rows[j][i] + "\"";
if (i != dt.Columns.Count - 1)
{
temp = temp + ",";
}
}
if (j == dt.Rows.Count - 1)
{
temp = temp + "}";
}
else
{

temp = temp + "},";
}

}
josn = josn + temp + "]";
return josn;
}
catch (Exception ex)
{
return "Codeing is Error----" + ex.ToString();
}

}
datatable 转json、