Miko
Miko

Reputation: 156

JSON: Creating an array node VB.NET

I'm new to this. And I hope someone can help me figure out how to do this So I have this import on my vb file

Import Namespace="System.Web.Script.Serialization"

Sure I can print JSONObjects however what I want is to print the objects with an array node.

Dim arr As New List(Of arr)()
arr.Add(New arr With{.arrId = 0, .arrName = "XXX"})
arr.Add(New arr With{.arrId = 1, .arrName = "YYY"})

If I serialize it, it will print this:

[{"arrId" : 0, "arrName" : "XXX"},{"arrId" : 1, "arrName" : "YYY"}]

But what I want is something that can specify those objects like the word "arrs" e.g.

["arrs":{"arrId" : 0, "arrName" : "XXX"},{"arrId" : 1, "arrName" : "YYY"}]

Any idea on how I can add "arrs" (list) inside this serialized array?

Thanks in advance!

Upvotes: 0

Views: 128

Answers (1)

EdSF
EdSF

Reputation: 12341

This is invalid:

["arrs":{"arrId" : 0, "arrName" : "XXX"},{"arrId" : 1, "arrName" : "YYY"}]

  • Your first item in the array is:
    "arrs":{"arrId" : 0, "arrName" : "XXX"}

  • which should be
    {"arrs":{"arrId" : 0, "arrName" : "XXX"}}

  • and the 2nd item would be
    {"arrId" : 1, "arrName" : "YYY"}

Though i don't think that's what you want/intended...


Disclaimer: My vb is rusty so improve as needed.

You'll need to "encapsulate" it within another object:

Class Container
        Public arrs As List(Of arr)
End Class

Class Child
        Public arrId As Integer
        Public arrName As String
End Class

So you can do something like this:

Sub Main()
    Dim arr As New List(Of Child)()
    arr.Add(New Child With {.arrId = 0, .arrName = "XXX"})
    arr.Add(New Child With {.arrId = 1, .arrName = "YYY"})

    'Object
    Dim foo As New Container With {.arrs = arr}

    'Array
    Dim bar As New List(Of Container)()
    bar.Add(New Container With {.arrs = arr})

    Console.WriteLine("foo serialized:  " + New JavaScriptSerializer().Serialize(foo))
    Console.WriteLine("bar serialized:  " + New JavaScriptSerializer().Serialize(bar))
End Sub

Which results in:

foo serialized:  {"arrs":[{"arrId":0,"arrName":"XXX"},{"arrId":1,"arrName":"YYY"}]}
bar serialized:  [{"arrs":[{"arrId":0,"arrName":"XXX"},{"arrId":1,"arrName":"YYY"}]}]

Hth...

Upvotes: 1

Related Questions