Laki Politis
Laki Politis

Reputation: 149

Can not deserialize JSON Object, because it's actually a poorly formatted Array

I'm trying to deserialize a JSON Object (which is an array), into a Generic List of a public class called County. Here's an excerpt from the JSON I receive:

{
    "Alachua":0,
    "Baker":1,
    "Bay":2,
    "Bradford":3,
    "Brevard":4,
    "Broward":5,
    "Calhoun":6,
    "Charlotte":7
}

Here's the class:

<Serializable()> _
Public Class County
    Private _name As String
    Private _code As Integer

    Public Property Code() As Integer
        Get
            Return Me._code
        End Get
        Set(value As Integer)
            Me._code = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return Me._name
        End Get
        Set(value As String)
            Me._name = value
        End Set
    End Property
End Class

However, because the JSON array isn't formatted correctly how I would normally expect it, I can not get it to serialize.

I'm currently using Newtonsoft:

Dim countyResponse As List(Of County) = ParseRequestJSON(Of List(Of County))(request)

And here's the exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Models.County]' 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) 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 'Alachua', line 2, position 12.

Any help would be appreciated, and please don't be scared off by the VB.net.

Upvotes: 1

Views: 1049

Answers (1)

Laki Politis
Laki Politis

Reputation: 149

Thanks to @user2864740 we have an answer. Deserialized into an IDictionary with a String Key and Integer Value. I then cycle through the IDictionary and add the counties to a list.

Dim countyResponse As IDictionary(Of String, Integer) = ParseRequestJSON(Of IDictionary(Of String, Integer))(request)

If IsNothing(countyResponse) = False Then
    For Each c In countyResponse
        Dim county As County = New County
        county.Code = c.Value
        county.Name = c.Key

        Counties.Add(county)
    Next
End If

Upvotes: 2

Related Questions