Link to home
Start Free TrialLog in
Avatar of RichardKline
RichardKline

asked on

How to deserialize JSON data list into .NET generic collection

I am working with a REST data source.  Single row returns aren't a problem as I can deserialize them using something like:
 JsonConvert.DeserializeObject(Of myInstantiatedClass)(httpResponseContent)

Retrieving a data list isn't a problem either.  But I am unable to deserialize it (using Newtonsoft.Json) into a .NET LIST collection.   A view of the simplified data looks like:
{
	"results":[
	{
		"id":"_198711_1"
	},
	{
		"id":"_198710_1"
	},
	]
}

Open in new window


I am using vb.net in this project but please feel free to send hints in c#!  I've tried various things including IEnumerate.  Simplifed snippet of the original code looks like this:
Public Class myClass
        Public Property id As String
End Class

...

 Dim myInstantiatedClass As New List(Of myClass)
        Dim response = Await client.GetAsync(Uri)
        If response.IsSuccessStatusCode Then
            Dim httpResponseContent = Await response.Content.ReadAsStringAsync()
            Try
                ' NEXT LINE IS WHERE ERRORS ARE THROWN 
                myInstantiatedClass = JsonConvert.DeserializeObject(Of List(Of InstantiatedClass ))(httpResponseContent)
            Catch jsonException As Newtonsoft.Json.JsonSerializationException
                Dim s As String = jsonException.Message
            End Try
        End If

Open in new window


The error code (using original variable and class names) reads:
"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Collections.Generic.List`1[BbRestApiExplorer.CourseGradeColumn]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly." 
"To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object." 
"Path 'results', line 1, position 11."

Open in new window


Any thoughts?   Thank you for your time.
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial