2014-09-24 69 views
0

我有一個函數從jsonblob獲取json字符串,反序列化它並在dataview中返回。我想知道我怎麼可以從數據視圖中的數據插入使用我的SQL數據庫vb.net反序列化json字符串並插入到SQL DB中

我的功能如下

Public Function GetJsonString() As DataView 
    Dim dsContactMeta As DataSet = Nothing 
    Dim dv As DataView = Nothing 
    'url declaration for REST_ContactMeta 
    Dim REST_ContactMetaURL As Uri = New Uri("http://jsonblob.com/api/jsonBlob/5420df11e4b00ad1f05ed29b") 
    Dim strJSONData As String = "" 
    Dim response As HttpWebResponse 
    Dim reader As StreamReader 

    Try 
     Dim httpWebRequest As HttpWebRequest = WebRequest.Create(REST_ContactMetaURL) 
     httpWebRequest.Method = WebRequestMethods.Http.Get 
     httpWebRequest.ContentType = "application/json" 

     response = httpWebRequest.GetResponse() 
     reader = New StreamReader(response.GetResponseStream) 

     strJSONData = reader.ReadToEnd 
     strJSONData = "[" & strJSONData & "]" 'had to wrap the raw JSON data with brackets for parsing purposes 
     Dim myXmlNode As System.Xml.XmlNode = JsonConvert.DeserializeXmlNode("{""root"":" + strJSONData + "}", "root") 'error is thrown if the JSON does not have a root element 
     ' Dim myXmlNode As System.Xml.XmlNode = JsonConvert.DeserializeXmlNode(strJSONData) 
     dsContactMeta = New DataSet("Test") 
     Try 
      dsContactMeta.ReadXml(New XmlNodeReader(myXmlNode)) 
      If dsContactMeta.Tables("root") Is Nothing Or dsContactMeta.Tables("root").Rows.Count = 0 Then 
       Return Nothing 'in case of error return nothing 
      Else 
       dsContactMeta.Tables("root").Columns("job_id").SetOrdinal(0) 'setting the field name as the first column 
       dv = New DataView 
       dv.Table = dsContactMeta.Tables("root") 
       Return dv 
      End If 
     Catch ex As Exception 
      Return Nothing 
     End Try 
    Catch ex As Exception 
     Return Nothing 'if for any reason the API has failed connecting to the server or other unknown error then return nothing 
    End Try 
End Function 

回答

0

插入記錄到數據視圖從數據庫,對於你需要閱讀DataView:

For Each rowView As DataRowView In dataView 
    Debug.Write(item & " ") 
    Dim row as DataRow = rowView.Row;  
    // Do something // 
    //insert into tablename(col1,col2,..) values(row['col1'],row['col2'],..) 
Next 
相關問題