将CSV文件转换为JSON

时间:2017-01-21 01:27:49

标签: json vb.net csv

我想发布接受JSON格式的CURL命令。我搜索了互联网,无法找到如何将CSV文件转换为JSON格式的vb.net代码,以便发布到API。任何建议表示赞赏。

以下是我用于发布到API的代码。 这个问题是独特的,因为它询问如何使用VB.Net 2013

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim wHeader As WebHeaderCollection = New WebHeaderCollection()
    wHeader.Clear()
    wHeader.Add("X-Appery-Database-Id: xxxxxxxxxxx")
    wHeader.Add("X-Appery-Session-Token:" & token)

    Dim sUrl As String = "https://api.appery.io/"
    'sUrl = System.Net.WebUtility.UrlEncode(sUrl)
    Dim wRequest As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(sUrl), HttpWebRequest)

    wRequest.ContentType = "application/json"

    wRequest.Headers = wHeader
    wRequest.Method = "POST"  

    Dim stream = wRequest.GetRequestStream()
    stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
    stream.Close()

    Dim wResponse As HttpWebResponse = DirectCast(wRequest.GetResponse(), HttpWebResponse)
    Dim sResponse As String = ""

    Using srRead As New StreamReader(wResponse.GetResponseStream())
       sResponse = srRead.ReadToEnd()
       Console.Write(sResponse)
       MsgBox(sResponse.ToString())

    End Using
End Sub

谢谢

1 个答案:

答案 0 :(得分:1)

我不知道数据能够提供更适用的示例。所以使用随机数据,起始csv:

  

名称,StockNum,颜色,现有量,价钱,ItemDate
  turpis Nullam sagitt,K94-ZS89,黑色,1,8.71,1 / 12/2017 12:00:00 AM   suscipit eget,Z25-XQKU,Topaz,0,14.48,1 / 14/2017 12:00:00 AM

然后,一个驱动它的类:

Public Class Something
    Public Property Name As String
    Public Property StockNum As String
    Public Property Color As String
    Public Property OnHand As Integer
    Public Property Price As Decimal
    Public Property ItemDate As DateTime

    Public Sub New()

    End Sub
End Class

使用JSON.NET和CSVHelper读取CSV并进行转换很简单:

Dim things As IEnumerable(Of Something)
Dim jstr As String

Using sr As New StreamReader("C:\Temp\Json\CSVTOJson.csv"),
    csv As New CsvReader(sr)

    things = csv.GetRecords(Of Something)()
    jstr = JsonConvert.SerializeObject(things)
End Using

请注意,这使用IEnumerable(但您可以使用列表或数组)。这使得它既经济又可能更快,特别是如果有许多记录。它们实际上不会被加载到您的应用程序中,只是传递给JSON.NET来读取和序列化它们。

结果:

[{
    "Name": "turpis Nullam sagitt",
    "StockNum": "K94-ZS89",
    "Color": "Black",
    "OnHand": 1,
    "Price": 8.71,
    "ItemDate": "2017-01-12T00:00:00"
}, {
    "Name": "suscipit eget",
    "StockNum": "Z25-XQKU",
    "Color": "Topaz",
    "OnHand": 0,
    "Price": 14.48,
    "ItemDate": "2017-01-14T00:00:00"
}, {
    "Name": "Proin faucibus arcu",
    "StockNum": "F64-WS5X",
    "Color": "Topaz",
    "OnHand": 6,
    "Price": 12.83,
    "ItemDate": "2017-01-18T00:00:00"
}
...
]