Help in VB.NET using Newtonsoft.Json

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 Label1 text be the points and Label2 be the name . Here is the JSON:

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

Thanks in advance.

    
asked by anonymous 04.09.2018 / 01:44

1 answer

1
Well I do not know why the code is inside a Timer , it should have a reason for that, but the question is about json to get 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 to move 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

These are the ways I see to solve your problem.

    
04.09.2018 / 02:17