Blease
Blease

Reputation: 1420

Decode JSON in Visual Basic 2010 Express

I am just learning the basics in VB 2010, and I am trying to design a program to maintain a database. I have a JSON string in the database that contains a list of image files and their relevant ID numbers. This is in JSON as a website also uses this data. The example code is

[{"ID": 0, "Path": "Image0.jpg"},{"ID": 1, "Path": "Image1.jpg"}, {"ID": 2, "Path": "Image2.jpg"},{"ID": 3, "Path": "Image3.jpg"}]

I have tried using JSON.NET, but I am a novice and don't know why it isn't working.

I wish for there to be a way I can return the image files, for example in php $DecodedArray[0] would work, I am looking for a way to replicate this in Visual Basic.

Imports System.Web.Script.Serialization
Module Module1

Public Class Target
    Public ID, Image As String
End Class

Sub Main()
    Console.Clear()
    Dim ser As New JavaScriptSerializer()
    Dim input As String = My.Computer.FileSystem.ReadAllText("JSONFile.txt")
    '[{"ID": 0, "Path": "Image0.jpg"},{"ID": 1, "Path": "Image1.jpg"}, {"ID": 2, "Path": "Image2.jpg"},{"ID": 3, "Path": "Image3.jpg"}]
    Console.WriteLine(input)
    Console.WriteLine()
    Dim output As Target = ser.Deserialize(Of Target)(input)
    Console.Write(output.ID.0)
    Console.ReadKey()
End Sub

End Module

With this code, I would like the output to be Image0.jpg

Note, I cannot upgrade from Visual Basic 2010 Express

Upvotes: 2

Views: 3154

Answers (1)

Joe Enos
Joe Enos

Reputation: 40403

Because your JSON has numeric keys instead of expected keys, it would be difficult to define a custom type to match it. I believe your best bet is to deserialize into a Dictionary(Of String, String) - this will deserialize properly, and you can read through the dictionary to get your items.

So:

Dim output = ser.Deserialize(Of Dictionary(Of String, String))(input)
For Each key As String In output.Keys
    Console.WriteLine("{0}: {1}", key, output(key))
Next

Normally when you define a regular type, you'd have to know the names of the JSON properties. Given your Target class, your JSON would actually look like:

[
    { "ID":"0", "Image":"Image0.jpg" },
    { "ID":"1", "Image":"Image1.jpg" },
    { "ID":"2", "Image":"Image2.jpg" }
]

And it would deserialize into an array of Target objects, rather than a single one. But if you're stuck with the JSON that you've got, the Dictionary is the way to go.

If you're able to use the cleaner JSON from here, your code is just about right. You just deserialize into an array instead, and you can access elements of that array. So:

Dim output = ser.Deserialize(Of Target())(input)
For i As Integer = 0 To output.GetUpperBound(0)
    Console.WriteLine("{0}: {1}", output(i).ID, output(i).Image)
Next

Upvotes: 4

Related Questions