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.
.NET ProgrammingRESTJSON

Avatar of undefined
Last Comment
Fernando Soto

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Fernando Soto

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23