Json.NET 是一套在Server端處理JSON格式資料的好套件
基本操作在最底下文章已提及
這邊要紀錄的是DataTable和JSON字串之間的互轉(而且Code很少)
下載紅框處
解壓縮後把Bin\Net資料夾底下的Newtonsoft.Json.dll放到Web Site專案的Bin目錄下即完成加入參考
再來看這次要實驗的資料集
接著開始寫程式
在.aspx設計畫面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> |
< form id = "form1" runat = "server" > |
< asp:Literal ID = "li_showData" runat = "server" />< hr /> |
< asp:Button Text = "把DataTable轉成JSON字串" ID = "btn_DataTableToJSONstr" runat = "server" |
OnClick = "btn_DataTableToJSONstr_Click" /> |
< asp:Button Text = "把JSON字串轉成DataTable" ID = "btn_JSONstrToDataTable" runat = "server" |
OnClick = "btn_JSONstrToDataTable_Click" />< hr /> |
< asp:GridView runat = "server" ID = "GridView1" /> |
Code-Behind
DataTable互轉JSON字串,重點只要一行程式碼就夠了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*要引用以下命名空間*/
using System.Data;
using System.Data.SqlClient;
/*Json.NET相關的命名空間*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public partial class _Default : System.Web.UI.Page
{
//DB連線字串
string connStr = @"Data Source=.\sqlexpress;Initial Catalog=NorthwindChinese;Integrated Security=True";
string sql = @"Select CategoryID,CategoryName,Description from Categories
Where CategoryID Between 1 And 5";
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 依據SQL語句,回傳DataTable物件
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
private DataTable queryDataTable(string sql)
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(this.connStr))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
}
return ds.Tables.Count > 0 ? ds.Tables[0] : new DataTable();
}
//把DataTable轉成JSON字串
protected void btn_DataTableToJSONstr_Click(object sender, EventArgs e)
{
//得到一個DataTable物件
DataTable dt = this.queryDataTable(this.sql);
//將DataTable轉成JSON字串
string str_json = JsonConvert.SerializeObject(dt, Formatting.Indented);
//JSON字串顯示在畫面上
li_showData.Text = str_json;
}
//把JSON字串轉成DataTable或Newtonsoft.Json.Linq.JArray
protected void btn_JSONstrToDataTable_Click(object sender, EventArgs e)
{
//Newtonsoft.Json.Linq.JArray jArray =
// JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JArray>(li_showData.Text.Trim());
//或
DataTable dt = JsonConvert.DeserializeObject<DataTable>(li_showData.Text.Trim());
//GridView1顯示DataTable的資料
//GridView1.DataSource = jArray; GridView1.DataBind();
GridView1.DataSource = dt; GridView1.DataBind();
}
}
執行結果:
使用ADO.net Entity Framework也可以輕鬆互轉JSON字串
using System.Collections.Generic; |
using System.Web.UI.WebControls; |
using NorthwindChineseModel; |
public partial class Default2 : System.Web.UI.Page |
protected void Page_Load( object sender, EventArgs e) |
protected void btn_EntitySetToJSONstr_Click( object sender, EventArgs e) |
using (NorthwindChineseEntities entities = new NorthwindChineseEntities()) |
IQueryable categories = from c in entities.Categories |
where c.CategoryID >= 1 && c.CategoryID <= 5 |
select new { c.CategoryID, c.CategoryName, c.Description }; |
string str_json = JsonConvert.SerializeObject(categories, Formatting.Indented); |
li_showData.Text = str_json; |
protected void btn_JSONstrToEntitySet_Click( object sender, EventArgs e) |
Newtonsoft.Json.Linq.JArray jArry = JsonConvert.DeserializeObject < Newtonsoft.Json.Linq.JArray>(li_showData.Text.Trim()); |
GridView1.DataSource = jArry; GridView1.DataBind(); |
另外
把JSON字串貼到Text頁籤的畫面上,可以再按Format排版
也可以再按Viewer進一步察看資料
如果JSON格式不符的話,會跳出一個alert訊息
算是輔助Debug的工具
2011.12.01 追加
既然都講到Server端的JSON字串,順便把JSONP字串也補完
if (! string .IsNullOrEmpty(Request.QueryString[ "callback" ])) |
str_json = Request.QueryString[ "callback" ] + "(" +str_json+ ");" ; |
沒有留言:
張貼留言