What's new

Help Vb.net question

Here is an example of Visual Basic code that shows how to work with JSON data:

Code:
Imports System.IO
Imports Newtonsoft.Json

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'Create an object to hold the data
        Dim data As New Dictionary(Of String, Object)()
        data.Add("name", "John Doe")
        data.Add("age", 30)
        data.Add("isMarried", True)

        'Serialize the object to JSON
        Dim json As String = JsonConvert.SerializeObject(data, Formatting.Indented)

        'Write the JSON to a file
        Dim filePath As String = "C:\Temp\data.json"
        File.WriteAllText(filePath, json)

        'Read the JSON from the file
        Dim jsonFromFile As String = File.ReadAllText(filePath)

        'Deserialize the JSON to an object
        Dim dataFromFile As Dictionary(Of String, Object) = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jsonFromFile)

        'Display the data in a messagebox
        MessageBox.Show("Name: " & dataFromFile("name").ToString() & vbCrLf & "Age: " & dataFromFile("age").ToString() & vbCrLf & "Married: " & dataFromFile("isMarried").ToString())
    End Sub

End Class

This code creates a dictionary object, adds some data to it, serializes it to JSON, writes the JSON to a file, reads the JSON from the file, deserializes it back to a dictionary object, and displays the data in a message box.

Note that this code requires the Newtonsoft.Json NuGet package to be installed.
 

Similar threads

Back
Top