I am trying to populate a listbox with the following data. The listbox is called lbxCamera and I need to fill it with the 3 rows of instructions.
I am supposed to use Newtonsoft.Json in the vb.net Winforms environment.
{
"lbxCamera":
[
{"Instructions":"2nd Instruction"},
{"Instructions":"2nd Instruction"},
{"Instructions":"3rd Instruction"}
]
}
Thanks,
I tried many things but none worked. I am used to pulling data from the database; this is my first time trying to get data from JSON files.
This is my solution: The JSON file is read in if it is found in the file system and is deserialized using Newtonsoft.Json
. You have to install Newtonsoft.Json
via the Nuget package manager. I simply called the class TestClass
because I didn't know what your object was called.
I think there was a lack of understanding because your JSON file consists of a list of dictionaries(of string, string)
. That's not so common. Because: Why have multiple dictionaries with 1 item when one dictionary containing multiple items would work?
Option Strict On
Imports Newtonsoft.Json
Public NotInheritable Class TestClass
<JsonProperty("lbxCamera")>
Public Property LbxCamera As List(Of Dictionary(Of String, String))
End Class
Option Strict On
Imports Newtonsoft.Json
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\new 1.json") Then
ListBox1.Items.Clear()
Dim jsonData As String = System.IO.File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\new 1.json")
Dim things As TestClass = JsonConvert.DeserializeObject(Of TestClass)(jsonData)
For Each dict As Dictionary(Of String, String) In things.LbxCamera
For Each kvp As KeyValuePair(Of String, String) In dict
ListBox1.Items.Add(kvp.Key & ": " & kvp.Value)
Next
ListBox1.Items.Add("---")
Next
End If
End Sub
End Class