自己总结的,输出到前端JSON的几种方法
第一种:利用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);
上一篇: 早饭是啥