user1257890
user1257890

Reputation: 23

Parse a JSON nested array with numbers and strings

I receive the following JSON response from a web server:

[
  [
    1499040000000,
    "0.01634790",
    "0.80000000",
    "0.01575800",
    "0.01577100",
    "148976.11427815",
    1499644799999,
    "2434.19055334",
    308,
    "1756.87402397",
    "28.46694368",
    "17928899.62484339"
  ]
]

How can I parse it to an array using System.Text.Json?
I've already tried String.Split() and String.Replace() (as the brackets and quotes appear in elements) but it's an "ugly" approach.

Any suggestions will be very much appreciated.

Upvotes: 0

Views: 257

Answers (1)

Jimi
Jimi

Reputation: 32248

That JSON represents an Array of arrays (well, a single nested array here).
You can parse it as a List(Of Double()) or List(Of List(Of Double)).

The mixed data Type (strings and numbers), can be converted to all numbers, setting a JsonSerializerOptions that specifies the NumberHandling to use, here set to AllowReadingFromString.

Dim options = New JsonSerializerOptions() With {
    .NumberHandling = JsonNumberHandling.AllowReadingFromString
}

Dim listOfDouble = JsonSerializer.Deserialize(Of List(Of Double()))(json, options)

You could also deserialize to a List(Of Object()) and perform the conversion later or just read the values as strings, calling .ToString() when you read an element of the List.

 Dim listOfObjects = JsonSerializer.Deserialize(Of List(Of Object()))(json)

Upvotes: 1

Related Questions