參考資料:
1.[ASP.net WebForm] 利用JSON.net 實現 DataTable轉JSON字串、JSON字串轉DataTable (程式碼短少) 以下的作法都是參考此篇
前置作業:必須先到 http://json.codeplex.com/ 下載JSON.NET套件,然後將套件載入道專案中
VB.NET 程式碼如下:
法1. 運用JArray陣列來產生JSON資料
'Json.NET相關的命名空間
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim ja As New JArray
Dim jo As New JObject
jo.Add("success", "1")
jo.Add("message", "successfully created.")
ja.Add(jo)
Dim str_json As String = JsonConvert.SerializeObject(ja, Formatting.Indented)
Response.Write("{" & Chr(34) & "test" & Chr(34) & ":" & str_json & "}")
End If
End Sub
法2.取出資料庫資料轉成JSON資料
Imports System
Imports System.Data
Imports System.Data.SqlClient
'Json.NET相關的命名空間
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim str_sql As String = Nothing
Dim p_value As String = Nothing
'假設要取得某一筆資料
str_sql = "Select test1,test2,test3 from test where test1=@test1 and test2=@test2"
'假設已經指定好參數,也就是sql指令的@test1,@test2,那就必須指定參數的值,如有多個參數值就已,號隔開
p_value = "台南市,某家商店"
'function queryDataTable(sql指令, 參數名稱, 參數值) 方法執行完會回傳DataTable
Dim dt As DataTable = queryDataTable(str_sql, "@test1,@test2", p_value)
Dim str_json As String = JsonConvert.SerializeObject(dt)
str_json = str_json.Replace(" ", "") '將空白取代掉
Response.Write("{" & Chr(34) & "test" & Chr(34) & ":" & str_json & "}")
End If
End Sub
Function queryDataTable(ByVal sql_str As String, ByVal pv As String, ByVal pv_value As String) As DataTable
Dim strsqlCon As String = "Server=127.0.0.1;Database=資料庫名稱;uid=帳號;pwd=密碼"
Dim sql_p() As String = Nothing
'可把split改成 Regex.Split,例如:Regex.Split("123<br/>456", "\<br\/\>") '\跳脫字元
sql_p = pv.Split(",") 'sql字串中的參數
Dim sqlvalue_p() As String = Nothing
sqlvalue_p = pv_value.Split(",") 'sql字串中的參數值
Dim ds As New DataSet()
Using conn As New SqlConnection(strsqlCon)
Dim command As SqlCommand = New SqlCommand(str_sql, conn)
Dim x_end As Integer = sql_p.Length - 1
For x As Integer = 0 To x_end
command.Parameters.AddWithValue(sql_p(x), sqlvalue_p(x)) '讓ADO.NET自行判斷型別轉換
Next
Dim da As New SqlDataAdapter()
da.SelectCommand = command
da.Fill(ds)
End Using
If ds.Tables.Count > 0 Then
Return ds.Tables(0)
Else
Return New DataTable()
End If
End Function
補充:
JSON資料轉成DataTable,並將資料傳給GridView1
'Label1.Text值 [{ "test1" : "台南市" , "test2" : "某家商店" },{ "test1" : "台南市" , "test2" : "某家商店1" },{ "test1" : "台南市" , "test2" : "某家商店2" }]
Dim str_data As String = Label1.Text.Replace(" ", "")
Dim dt As DataTable = JsonConvert.DeserializeObject(Of DataTable)(str_data)
GridView1.DataSource = dt
GridView1.DataBind()
以上 End
沒有留言:
張貼留言