[英]JSON (newtonsoft) deserialize using MS Access field names, in VB.net
我正在嘗試反序列化通常需要兩個類的JSON字符串,我想用從MS Access字段名稱獲取的數組中的項目替換這些類之一(請參見注釋掉的類)。
這樣,如果數據庫表發生更改,我不必修改代碼(僅訪問表本身和源JSON)。
在下面的代碼中,我停留在如何定義公共屬性“ Data”以及js.data(SampleClass.data)的定義上。 看到我的?????? 問號! 我正在嘗試使用列表(字符串)來存儲字段名稱,並希望將這些列表存儲在Data(0),Data(1),Data(2)等中,因此每個Data元素都具有字段名稱列表,以及每個記錄的關聯值。
我想按以下方式獲取數據:js(SampleClass)包含未知數量的“數據”列表(根據JSON字符串中的數量),每個列表均包含從Access獲取的字段名稱。 然后,我想將結果插入到MS Access表中,並將每個“數據”列表作為一條記錄。
注意:我用非常小的JSON字符串提取替換了“ rawresp”(來自HTTP請求)。
任何人都可以幫忙,不勝感激。 我希望這一切都有意義
謝謝阿德里安
Imports Newtonsoft.Json
'link to create classes
'http://www.httputility.net/json-to-csharp-vb-typescript-class.aspx
'example of json script
'http://stackoverflow.com/questions/21676708/simple-working-example-of-json- net-in-vb-net
'Public Class Datum
'Public ABC As String
'Public DEF As String
'Public GHI As Integer
'Public JKL As Integer
'Public MNO As String
'Public PQR As String
'Public STU As String
'Public VWX As String
'Public YZA As String
'Public BCD As Integer
'Public EFG As Integer
'Public HIJ As String
'Public KLM As String
'Public NOP As String
'Public QRS As String
'End Class
Public Class SampleClass
Public Property Success As Boolean
?????? Public Property Data As List(Of String)
End Class
Module JSON
Sub getjson()
'Try
cleanup(Nothing, Nothing)
Dim daoEngine As New dao.DBEngine, db As dao.Database
db = daoEngine.OpenDatabase(DBPath)
Dim rst As dao.Recordset = Nothing
rst = db.OpenRecordset("tUnit") 'open table
Dim fields(rst.Fields.Count) As String
For j = 0 To rst.Fields.Count
fields(j) = rst.Fields(j).Name
Next
Dim js As New SampleClass
?????? Dim js.data As List(Of js.Data)(fields)
Dim rawresp As String
Dim request As Net.HttpWebRequest
Dim response As Net.HttpWebResponse = Nothing
Dim reader As IO.StreamReader
request = DirectCast(Net.WebRequest.Create("http://10.32.27.17/api/endusers"), Net.HttpWebRequest)
response = DirectCast(request.GetResponse(), Net.HttpWebResponse)
reader = New IO.StreamReader(response.GetResponseStream())
rawresp = reader.ReadToEnd()
js = JsonConvert.DeserializeObject(Of SampleClass)("{""success"":true,""data"":[{""ABC"":""Something"",""DEF"":""Other""},{""ABC"":""This"",""DEF"":""That""}]}")
?????? For Each i As String In js.Data
rst.MoveFirst()
Do While Not rst.EOF 'look through to end of table
If n(rst(i(1)).Value) Like i(1) Then
For Each j In i
rst.Edit()
rst(j).Value = j
rst.Update()
Next
End If
rst.MoveNext() 'move to next record
Loop
Next
cleanup(db, Nothing)
'Catch ex As Exception
' Debug.Print(ex.Message)
'End Try
End Sub
End Module
數據不只是List(of Dictionary(of string, string))
嗎?
因此Data(0).Item("ABC") = "Something"
...等等。
雖然不確定newtonsoft如何反序列化,所以這是一個經典的即席堆棧式答案(例如,值得您為此付出代價);)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.