用 Json.Net 產生 Json 的 範例
1. 安裝Json.net套件
2. 加入命名空間
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
3. 透過 泛行處理常式 (ashx),用 Json 範例如下:
(a) 用DataTable產生 Json
DataTable dt = new DataTable();
//...略
//將DataTable轉成JSON字串
string str_json = JsonConvert.SerializeObject(dt, Formatting.Indented);
context.Response.ContentType = "text/plain";
context.Response.Write(str_json);
(b) 用物件產生 JSON
public class result
{
public string id { get; set; }
public string name { get; set; }
}
//--- 略 ---
result rlt2 = new result() { id = "222", name = "FFF" };
string json = JsonConvert.SerializeObject(rlt2);
context.Response.ContentType = "text/plain";
context.Response.Write(json);
(c) 用 List 產生 JSON
public class result
{
public string id { get; set; }
public string name { get; set; }
}
//--- 略 ---
List<result> lst = new List<result>();
lst.Add(new result() { id = "111", name = "AAA" });
lst.Add(new result() { id = "222", name = "FFF" });
string json = JsonConvert.SerializeObject(lst);
context.Response.ContentType = "text/plain";
context.Response.Write(json);