第一種:利用MODEL拼成要輸出JSON的對象。再用JSON.NET轉成JSON輸出到前端(這種常用,就不舉例了。) 第二種:利用table拼成JSON數據格式,再用JSON.NET轉成JSON輸出到前端: dt = new DataTable(); dt.Columns.Add(new DataC ...
第一種:利用MODEL拼成要輸出JSON的對象。再用JSON.NET轉成JSON輸出到前端(這種常用,就不舉例了。)
第二種:利用table拼成JSON數據格式,再用JSON.NET轉成JSON輸出到前端:
dt = new DataTable();
dt.Columns.Add(new DataColumn("列頭",typeof(string)));
dt.Columns.Add(new DataColumn("object", typeof(object)));
DataRow dr = dt.NewRow();
dr[0] = "abc";
DataTable dt2 = dt.Clone();
dt2.Columns.Add("defaultdata", typeof(string));
DataRow dr2 = dt2.NewRow();
dr2[0] = "defgijk";
dr2["defaultdata"] = "cccc";
dt2.Rows.Add(dr2);
dr[1] = dt2;
dt.Rows.Add(dr);
GridView1.DataSource = dt.Rows[0][1];
GridView1.DataBind();
Label1.Text = JsonConvert.SerializeObject(dt);
第三種:用JSON.net自帶的JOBJECT,拼成JSON格式,轉成JSON在前端輸出:
JObject obj = new JObject();
obj.Add(new JProperty("Status", "S"));
obj.Add(new JProperty("TotalCount", totalCount));
JArray array = new JArray();
if (result != null)
{
foreach (var item in result)
{
array.Add(
new JObject(
new JProperty("X", item.X)
, new JProperty("XXX", item.XX)
, new JProperty("XXXXX", item.XXX)
, new JProperty("XXXxxxxx", item.XXXX)
, new JProperty("xxxxxxxxxxx", item.XXXXX)
, new JProperty("xxxxxxxxxxxxxx", item.XXXXXX)
, new JProperty("xxxxxxxxxxxxxxxxxxxxxxxxxxxx", item.XXXXXXX)
, new JProperty("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", item.XXXXXXXX)
, new JProperty("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", item.XXXXXXXXX)
, new JProperty("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", item.XXXXXXXXXX)
, new JProperty("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", item.XXXXXXXXXXX)));
}
obj.Add(new JProperty("WorkOrderManagerList", array));
Response.Write(JsonConvert.SerializeObject(obj));
第四種:利用array數組和hashtable拼成JSON格式,轉成JSON在前端輸出:
ArrayList eventList = new ArrayList();
Hashtable hx = new Hashtable();
hx.Add("eventid", 1);
hx.Add("eventname", "聖誕節");
hx.Add("eventdate", "2018-08-25");
hx.Add("eventlocation", "公司會議中心");
for (int i = 0; i < 3; i++)
{
Hashtable ht = new Hashtable();
ht.Add("eventid", i + 1);
ht.Add("eventname", "聖誕節");
ht.Add("eventdate", hx);
ht.Add("eventlocation", "公司會議中心");
eventList.Add(ht);
}
JavaScriptSerializer ser = new JavaScriptSerializer();
String jsonStr = ser.Serialize(eventList);
Response.Write(jsonStr);