使用VB.NET创建动态JSON数组

时间:2016-10-25 02:41:58

标签: javascript arrays json vb.net

我需要创建一个动态数组并将其作为JSON数组传递,以便使用Morris对其进行图形化。 据说,使用VB.NET创建一个JSON数组是这样的:

 Dim xArray(2)

 xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 1600}
 xArray(1) = New With {Key .TradingDay = "Day2", .Seller1 = 2300, .Seller2 = 1850}
 xArray(2) = New With {Key .TradingDay = "Day3", .Seller1 = 4970, .Seller2 = 3560}

然而,在这种情况下,卖家是动态的。客户可以(从列表框中)选择要选择的卖家。所以它可以是:

 Dim xArray(2)

 xArray(0) = New With {Key .TradingDay = "Day1", .Seller2 = 1600, .Seller3 = 2550, .Seller4 = 3600}
 xArray(1) = New With {Key .TradingDay = "Day2", .Seller2 = 1850, .Seller3 = 890, .Seller4 = 3456}
 xArray(2) = New With {Key .TradingDay = "Day3", .Seller2 = 3560, .Seller3 = 10890, .Seller4 = 2850}

有没有办法创建动态数组并将其作为JSON数组传递?

1 个答案:

答案 0 :(得分:0)

您需要使用导入Newtonsoft.Json 来序列化数组。稍微修改这个例子,将帮助您实现您想要的。 基本上在这个例子中,我创建了两个类(Product& Seller),您可以将其称为模型类。你需要根据你的数据修改循环。

 Public Class Product
      Public Property TradingDay As String
      Public Property sellers As List(Of Seller)
      End Class

      Public Class Seller
      Public Property SellerName As String
      Public Property price As String
      End Class

     Dim mainList as List(of Product)

     your main for Loop

        Dim product As New Product()
        product.TradingDay = "Day1"
        dim sellerList as List(of Seller)
            your loop for sellers
                dim seller as new Seller()
                seller.SellerName ="name should be here"
                seller.price="your price"
                sellerList.add(seller)
            next
        product.sellers = sellerList
        mainList.add(product)
      Next
      Dim output As String = JavaScriptConvert.SerializeObject(mainList)

上面的例子中可能存在语法错误,因为我触及vb已经很长时间了。但这种方式肯定会帮助你