2014-03-05 62 views
0

我找不到任何地方。我正在使用牛頓JSON控件,並試圖循環訪問我的記錄,並將每條記錄寫入一個JSON文件中。以下是我正在嘗試但不能正確的。我得到令牌路徑錯誤和各種各樣。我不知道在哪裏寫JSON的開始和結束。如何在JSON文件中寫入多個記錄?

謝謝! 沃倫

 Dim sb As New StringBuilder() 
    Dim sw As New StringWriter(sb) 
    Using writer As JsonWriter = New JsonTextWriter(sw) 
     writer.Formatting = Formatting.Indented 
     writer.WriteStartObject() 

     Dim ConnString7 As String = "removed" 
     Dim SQLConn As New SqlConnection() 
     Dim SQLCmd As New SqlCommand() 
     SQLCmd.Connection = SQLConn 
     SQLConn.ConnectionString = ConnString7 
     SQLCmd.CommandType = CommandType.StoredProcedure 
     SQLCmd.CommandText = "Sproc_Here" 
     SQLConn.Open() 
     Dim reader As SqlDataReader 
     reader = SQLCmd.ExecuteReader() 
     While reader.Read() 
      MsgBox("Start") 
      writer.WritePropertyName("CardDate") 
      writer.WriteValue(reader("CardDate").ToString()) 
      writer.WritePropertyName("EditDate") 
      writer.WriteValue(reader("EditDate").ToString()) 
      writer.WritePropertyName("Activity") 
      writer.WriteValue(reader("Activity").ToString()) 
      writer.WritePropertyName("Location") 
      writer.WriteValue(reader("Location").ToString()) 
      MsgBox("End") 
     End While 
     reader.Close() 
     SQLConn.Close() 

     writer.WriteEnd() 
     writer.WriteEndObject() 

     MsgBox(sb.ToString) 

     Response.Clear() 
     Response.ContentType = "application/json; charset=utf-8" 
     Response.Write(sb.ToString) 
     Response.End() 

回答

0

每個記錄將成爲一個JSON對象,你想擁有他們的倍數,所以他們需要被封閉在一個JSON陣列。所以像這樣:

Dim sb As New StringBuilder() 
    Dim sw As New StringWriter(sb) 
    Using writer As JsonWriter = New JsonTextWriter(sw) 

     writer.Formatting = Formatting.Indented 

     ' ... code to set up SQLCmd omitted for brevity ... 
     Dim reader As SqlDataReader = SQLCmd.ExecuteReader() 

     writer.WriteStartArray() 

     While reader.Read() 
      writer.WriteStartObject() 
      writer.WritePropertyName("CardDate") 
      writer.WriteValue(reader("CardDate").ToString()) 
      writer.WritePropertyName("EditDate") 
      writer.WriteValue(reader("EditDate").ToString()) 
      writer.WritePropertyName("Activity") 
      writer.WriteValue(reader("Activity").ToString()) 
      writer.WritePropertyName("Location") 
      writer.WriteValue(reader("Location").ToString()) 
      writer.WriteEndObject() 
     End While 

     writer.WriteEndArray() 

     ' ... code to close connection and write response omitted ... 

    End Using