vb.net从DataTable中的字符串获取json中的值

时间:2018-03-25 13:01:54

标签: json vb.net

这是我的json like string:

{
    "ProductGroupId": "3",
    "ProductGroupName": "Frisdranken",
    "ProductId": "139",
    "ProductName": "Cola",
    "Quantity": 1,
    "QuantityUnit": "P",
    "SellingPrice": 2.7,
    "VatRateId": "A",
    "DiscountLines": []
}, {
    "ProductGroupId": "3",
    "ProductGroupName": "Frisdranken",
    "ProductId": "146",
    "ProductName": "Plat water",
    "Quantity": 1,
    "QuantityUnit": "P",
    "SellingPrice": 2.6,
    "VatRateId": "A",
    "DiscountLines": []
}

如何在数据表中获取“ProductName”和“Quantity”?

1 个答案:

答案 0 :(得分:0)

假设你的json是一个数组而你错过了封闭的[...],你可以:

Dim json As String = "[{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""139"",""ProductName"":""Cola"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.7,""VatRateId"":""A"",""DiscountLines"":[]},{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""146"",""ProductName"":""Plat water"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.6,""VatRateId"":""A"",""DiscountLines"":[]}]"

'Use JSON.Net to obtain a JArray
Dim jobj As JArray = JsonConvert.DeserializeObject(json)

'Extract just the fields you want from the data with a Linq projection into
'anonymous type with ProductName and Quantity fields
Dim ProductsAndQuantities = jobj.Select(Function(j)
                                            Return New With {
                                                .ProductName = j("ProductName"), 
                                                .Quantity = j("Quantity")}
                                        End Function)

'build your DataTable
Dim dt As DataTable = New DataTable()
dt.Columns.Add("ProductName")
dt.Columns.Add("Quantity")

'Load the data table
For Each item In ProductsAndQuantities
    Dim dr As DataRow = dt.NewRow()
    dr("ProductName") = item.ProductName
    dr("Quantity") = item.Quantity
    dt.Rows.Add(dr)
Next