lulutanseco lulutanseco - 2 years ago 80 Question

Create a dynamic JSON array using VB.NET

I need to create a dynamic array and pass it as JSON array in order to graph it using Morris.
Supposedly, to create a JSON array using VB.NET is like this:

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}

However, in this case, the Sellers are dynamic. The client can choose (from a listbox) the sellers to be selected. So it can be:

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}

Is there any way to create a dynamic array and pass it as JSON array?

Answer Source

You need to use Import Newtonsoft.Json for serializing array. with slight modification to this example, will help you achieve what you want. basically in this example, I have created two classes(Product & Seller) you can refer to as model classes. you need to modify the loop according to your data.

 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"
        product.sellers = sellerList
      Dim output As String = JavaScriptConvert.SerializeObject(mainList)

There can be syntax error in the above example as its been a long time since i touched vb. but this way will surely help you out

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download