Deserialize json array in vb.net

26,048

I agree that the JSON library you need to use is Json.NET found at http://json.codeplex.com/

So, given your example JSON array, I made the following classes that can be used for serializing and deserializing:

Public Class Item
    Public Property [property]() As Integer
    Public Property listofstuff() As Stuff()
    Public Property lastproperty() As Integer
End Class

Public Class Stuff
    Public Property anotherproperty() As String
    Public Property yetanother() As String
End Class

Then all you need is the following code to be able to access the data in roughly the way you wanted to:

Dim Items = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Item())(json)
Dim MyList = Items.ToDictionary(Function(x) x.property)
Dim Stuff = MyList(96).listofstuff(0)

If your intent with the listofstuff property array was to store any string pair then use this definition for Item (and you also won't need the Stuff class):

Public Class Item
    Public Property [property]() As Integer
    Public Property listofstuff() As Dictionary(Of String, String)()
    Public Property lastproperty() As Integer
End Class
Share:
26,048
Cyclone
Author by

Cyclone

I'm a php web developer. I'm mostly done with my secret project. Hold out just a bit longer! I keep getting distracted by various things, like Project Euler, but at least it's entertaining. When in doubt, Fnord!

Updated on July 09, 2022

Comments

  • Cyclone
    Cyclone almost 2 years

    I have a json array which is formatted as follows:

    [
      {
        "property":96,
        "listofstuff":[
          {
            "anotherproperty":"some text here",
            "yetanother":"text goes here too"
          }
        ],
        "lastproperty":3001
      },
     <rest of array>
    ]
    

    How can I deserialize this in such a way that I can have a list of objects indexed by property? Meaning, I want to be able to access the data like this: MyList(96).lastproperty or MyList(96).listofstuff.yetanother and have it return the proper datatype too? Is that even possible in vb.net?

  • Cyclone
    Cyclone over 13 years
    And how would i go about using that for this purpose?
  • Sean
    Sean over 13 years
    from the author (see the LINQ to JSON example) james.newtonking.com/pages/json-net.aspx Alternative if you want to strongly type you classes: msdn.microsoft.com/en-us/library/bb412179.aspx
  • Cyclone
    Cyclone over 13 years
    Items.ToDictionary does not seem to exist?
  • Cyclone
    Cyclone over 13 years
    Also if this code works as simply as it seems it will, then you've just saved me several hours of debugging ugly regexes.
  • Cyclone
    Cyclone over 13 years
    Scratch that. I forgot a parenthesis.