barsan barsan - 1 month ago 9
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:


{"idDoc":18,"idDocRipristino":0,"relCau":1,"numDoc":"2","data":"2016-10-17T00:00:00","relTavolo":3,"apertura":"4","orario":"2016-10-17T00:00:00","idAna":0,"nominativo":"5","relOpe":6,"totale":7.0,"note":"8","idAsp":0,"romana":0,"relOpe_Port":0}


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()
Else
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);
}
else
{
return null;
}
}
}


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

Answer

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