JSON.Net Cannot deserialize the current JSON array

倾然丶 夕夏残阳落幕 提交于 2019-12-13 07:28:14

问题


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"
  }
] 

回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/40809394/json-net-cannot-deserialize-the-current-json-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!