DoomBots
DoomBots

Reputation: 13

JSON.Net Cannot deserialize the current JSON array

I'm attempting to make a program for LoL that would allow users to view specific stats for a player. However, I'm having issues..

The error I'm getting is.

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WindowsApplication1.Form1+Rootobject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

This is the code that I have so far.

Public Class Rootobject
        Public Property games As Integer
        Public Property winPercent As Double
        Public Property order As List(Of Class1)
        Public Property role As String
    End Class

    Public Class Class1
        Public Property order() As String
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim client As WebClient = New WebClient()
        client.Headers.Add("Content-Type", "application/json")
        Dim reply As String = client.DownloadString("skills/mostPopular?api_key=")
        Dim rootObject As Rootobject = JsonConvert.DeserializeObject(Of Rootobject)(reply)
        MsgBox(rootObject.games)
    End Sub 

Here is how the JSON looks like. (Id post a URL but it requires an API key)

[
  {
    "games": 1650,
    "winPercent": 46.9,
    "order": [
      "Q",
      "W",
      "E",
      "Q",
      "Q",
      "R",
      "Q",
      "W",
      "Q",
      "W",
      "R",
      "W",
      "W",
      "E",
      "E",
      "R",
      "E",
      "E"
    ],
    "role": "Support"
  },
  {
    "games": 9769,
    "winPercent": 51.8,
    "order": [
      "Q",
      "W",
      "E",
      "Q",
      "Q",
      "R",
      "Q",
      "W",
      "Q",
      "W",
      "R",
      "W",
      "W",
      "E",
      "E",
      "R",
      "E",
      "E"
    ],
    "role": "Middle"
  }
] 

Upvotes: 0

Views: 816

Answers (2)

Fabio
Fabio

Reputation: 32445

Your Json string is array of RootObjects. Change expected object to the list

Dim objects As List(Of Rootobject) = JsonConvert.DeserializeObject(Of List(Of Rootobject))(reply)

Dim root As Rootobject = objects.First()
MessageBox.Show(root.games)

And second error noticed by @Nkosi - change Rootobject as he suggest

Upvotes: 3

Nkosi
Nkosi

Reputation: 247018

Update the root object. The JSON in question resolves to the below class

Public Class Rootobject
    Public Property games As Integer
    Public Property winPercent As Double
    Public Property order As String()
    Public Property role As String
End Class

You are also trying to deserialize the array into a single object when the data is a collection.

Dim rootObjects As List(Of Rootobject) = JsonConvert.DeserializeObject(Of List(Of Rootobject))(reply)

Upvotes: 3

Related Questions