0

Trying to figure out how to use Newtonsoft with VB.net. I'm parsing a variety of information and would love to know how to separate it all.

Here's my code:

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Module Module1

    Public Sub Main()
        Dim json As String = "{""name"":""Sam"",""age"":""23"",""scores"":[{""main"":12,""side"":40},{""main"":123,""side"":51}],""final"":{""test1"":0,""test2"":2}}"
        Dim finalInfo = JsonConvert.DeserializeObject(Of information)(json)

        Console.WriteLine(finalInfo.name)

        Console.ReadKey()

    End Sub

    Public Class information
        Public name As String
        Public age As String
    End Class

End Module

As you can see I'm already able to parse objects name and age but not the array scores and the object with multiple values final.

Any help with this would be deeply appreciated, thank you!

  • 1
    Paste your JSON in [JSON Utils](https://jsonutils.com/) to generate classes in the VB.Net language. If the JSON is relatively simple, you can also use Visual Studio's `Edit -> Paste Special -> Paste JSON As Classes` tool. -- Of course you need to copy/paste the real JSON, not the formatted string you have here (you could print that string to the Output Window, copy the result and paste it somewhere else) – Jimi May 29 '22 at 06:22
  • I mean, in relation to the code presented here, for testing purposes. In real cases, you don't build JSON strings *manually*, you serialize a class model or read/receive the JSON from some source. – Jimi May 29 '22 at 06:40
  • If you don't know in advance the properties your JSON will contain, you could deserialize your JSON to a `JObject` (the Json.NET equivalent to `XElement`) as shown in [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/q/4535840/3744182). Or add a `[JsonExtensionData]` property to your `information` model to capture unknown properties as shown in [Deserialize json with known and unknown fields](https://stackoverflow.com/q/15253875/3744182). In fact, while your question is a little unclear, it may be a duplicate of one of those two, agree? – dbc May 29 '22 at 14:56

1 Answers1

0

you need this class information

 Public Class information
        Public Property name As String
        Public Property age As String
        Public Property scores As Score()
        Public Property final As Final
    End Class

Public Class Score
        Public Property main As Integer
        Public Property side As Integer
    End Class

    Public Class Final
        Public Property test1 As Integer
        Public Property test2 As Integer
    End Class

   
Serge
  • 40,935
  • 4
  • 18
  • 45