ZEQUET ZEQUET - 5 months ago 11
JSON Question

I am trying to deserialize a JSON but Newtonsoft.Json is throwing this error


Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Retail_Web.Helpers+Sale1[]' 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 'Sale.saleID', line 1, position 73.



JSON :

{
"Sale": {
"saleID": "54",
"timeStamp": "2016-06-10T13:03:16+00:00",
"discountPercent": "0"
}
}


Model :

Public Class Helpers
Public Property Sale As Sales()

Public Class Sales
Public Property saleID As String
Public Property timeStamp As String
Public Property discountPercent As String
Public Property completed As String
End Class
End Class


And, this is the code causing the error :

Dim OrdersReceiptList2 As Helpers

OrdersReceiptList2 = JsonConvert.DeserializeObject(Of Helpers)(File.ReadAllText("c:\test.json"))
MsgBox(OrdersReceiptList2.Sale(0).saleID)

Answer

Sale is not an array. Try this instead :

Public Class Helpers
    Public Property Sale As Sales 'removed ()

    Public Class Sales 
        Public Property saleID As String
        Public Property timeStamp As String
        Public Property discountPercent As String
        Public Property completed As String
    End Class
End Class

MsgBox(OrdersReceiptList2.Sale.saleID)