Starlays Starlays - 1 year ago 134 Question

JSON JsonConvert.DeserializeObject error

I'm having a problem that I don't know how to solve.

I'm trying to resolve the error:

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

I have found similar pages on stack-overflow and tried what was proposed in the answers but I'm not able to figure out what is the problem.

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Class jsonPrjData
Public Property sapcode() As String
Public Property prjCode() As String
Public Property prjDescript() As String
End Class

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://localhost/json/")
Dim obj = JsonConvert.DeserializeObject(Of jsonPrjData)(result)
End Sub
End Class

And the JSON looks like this:


Answer Source

The key part of the error message is: Cannot deserialize the current JSON array (e.g. [1,2,3]). The message scrolls giving a clearer idea what to do:

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

The square brackets indicate the data is an array (e.g. [1, 2, 3]) and also the fact that there is obviously 2 repeating sets of data of identical structure there. So:

' Note the added ()
Dim prjData = JsonConvert.DeserializeObject(Of jsonPrjData())(result)

As the latter part of the error message indicates, you can also deserialize to a List(of T):

Dim prjList = JsonConvert.DeserializeObject(Of List(Of jsonPrjData))(result)

Of course since the target object is declared locally, they will only exist in that click event.