barsan barsan - 4 months ago 22
JSON Question

Why getting error Cannot deserialize the current JSON object?

I have a web asp API which is returning value in the following format:


And I'm using the below code from a winform Application to bind the data with devexpress gridview but I'm getting below error:

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

Here is my winform code to access the API and reading the data using JSON:

Async Sub GetDocumenti(idDoc As Integer)
Dim Uri As String = "http://localhost:53917/api/Documenti/GetByIdDoc"
Using client = New HttpClient()
Using response = Await client.GetAsync([String].Format("{0}/{1}", Uri, idDoc))
If response.IsSuccessStatusCode Then
Dim DocumentisonData = Await response.Content.ReadAsStringAsync()
GridCtrlDocumenti.DataSource = JsonConvert.DeserializeObject(Of Documenti())(DocumentisonData).ToList()
Dim result = DevExpress.XtraEditors.XtraMessageBox.Show("Sorry no data found!!", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

End If
End Using
End Using
End Sub

This is my Repository :

public DocumentiModel GetByIdDoc(int id)
using (var dbCtx = new USDevEntities())
var documenti = dbCtx.Documentis.Where(x => x.IDDoc == id).FirstOrDefault();
if (documenti != null)
return ConvertTo(documenti);
return null;

Please suggest me how do I solve this error. Thanks.


Your JSON represents a single object, while your code is trying to deserialize into an array. That won't work.

Change this line:

GridCtrlDocumenti.DataSource = JsonConvert.DeserializeObject(Of Documenti())(DocumentisonData).ToList()

To this:

Dim list As List(Of Documenti) = New List(Of Documenti)
list.Add(JsonConvert.DeserializeObject(Of Documenti)(DocumentisonData))
GridCtrlDocumenti.DataSource = list