Help in VB.NET using Newtonsoft.Json

Asked

Viewed 132 times

1

Hello, I have this code:

Imports System.IO
Imports Newtonsoft.Json.Linq

Public Class Form1
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim channel As JObject = JObject.Parse(File.ReadAllText("C:\stats.json"))
    End Sub
End Class

I want to make the text of Label1 be the points and Label2 to be the name. Here is the JSON:

{
  'points': 0,
  'name': 'John Doe'
}

From now on, thank you.

  • Why is the code inside a Timer? That’s the way it’s gonna work?

1 answer

1


Well I don’t know why the code is inside a Timer, there must be a reason for this, but the question relates to json to take each value points and name and pass respectively to Label1 and Label2, with the method GetValue will retrieve each item and it is very simple now move on to the two Labels, example:

Dim channel As JObject = JObject.Parse(File.ReadAllText("./stats.json"))
Dim points = channel.GetValue("points").ToString()
Dim name = channel.GetValue("name").ToString()

Label1.Text = points
Label2.Text = name

Another way is to encode a class with the following fields:

Public Class Rootobject
    Public Property points As Integer
    Public Property name As String
End Class

and deserialize the content of json, example:

Dim RootObject = DirectCast(Newtonsoft _
    .Json _
    .JsonConvert _
    .DeserializeObject(File.ReadAllText("./stats.json"), 
            GetType(Rootobject)), Rootobject)


Label1.Text = RootObject.points.ToString()
Label2.Text = RootObject.name

Are the ways I see to solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.