VB.NET JSON Deserialization javascriptserializer

281 views Asked by At

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.

1

There are 1 answers

0
David On

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)