0

Hello how can I deserialize the following JSON structure with VB.NET?

{
    "ok": true,
    "license": "CC BY 4.0",
    "data": "TEST",
    "stations": {
        "station1": {
            "status": "open",
            "price1": 1.234,
            "price2": 1.234,
            "price3": 1.234
        },
        "station2": {
            "status": "open",
            "price1": 1.234,
            "price2": 1.234,
            "price3": 1.234
        }
    }
}

Important the number of stations could be different. Here in this example are two stations.

Thank you very much.

  • 2
    With [System.Text.Json](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0). – Hel O'Ween May 02 '22 at 15:27
  • Does this answer your question? [Deserializing JSON in Visual basic](https://stackoverflow.com/questions/20079177/deserializing-json-in-visual-basic) – Étienne Laneville May 02 '22 at 15:49
  • @ÉtienneLaneville thank you. I forgot to write that I want to use a class to handle it but my problem is the transfer from the solution you answered to my individual problem. – user17360738 May 02 '22 at 17:05

1 Answers1

0

Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. Using either Newtonsoft.Json or System.Text.Json, you can tidy the classes up a little bit using decorators so that you can conform to .NET standard naming conventions while still serializing the JSON to the expected values.

This is how the class definitions would look tidied up a bit:

Public Class Response
    <JsonProperty("ok")>
    Public Property Ok As Boolean

    <JsonProperty("license")>
    Public Property License As String

    <JsonProperty("data")>
    Public Property Data As String

    <JsonProperty("stations")>
    Public Property Stations As IEnumerable(Of Station)
End Class

Public Class Station
    <JsonProperty("status")>
    Public Property Status As String

    <JsonProperty("price1")>
    Public Property Price1 As Single

    <JsonProperty("price2")>
    Public Property Price2 As Single

    <JsonProperty("price3")>
    Public Property Price3 As Single
End Class

Now all you need to do is call the DeserializeObject method, using your Response class as the type and passing your JSON literal. For example:

Dim literal = "{
  ""ok"": true,
  ""license"": ""CC BY 4.0"",
  ""data"": ""TEST"",
  ""stations"": {
    ""station1"": {
      ""status"": ""open"",
      ""price1"": 1.234,
      ""price2"": 1.234,
      ""price3"": 1.234
    },
    ""station2"": {
      ""status"": ""open"",
      ""price1"": 1.234,
      ""price2"": 1.234,
      ""price3"": 1.234
    }
  }
}"
Dim conversion = JsonConvert.DeserializeObject(Of Response)(literal)
David
  • 5,877
  • 3
  • 23
  • 40