我有一个web asp API,它以下列格式返回值:
{" idDoc":18," idDocRipristino":0," relCau":1," numDoc":" 2""数据":" 2016-10-17T00:00:00"" relTavolo":3,"春季" :" 4"" orario":" 2016-10-17T00:00:00"" idAna":0,&#34 ; nominativo":" 5"" relOpe":6,"驻颜":7.0"注意":" 8"" idAsp":0,"协会":0," relOpe_Port":0}
我使用winform应用程序中的以下代码将数据与devexpress gridview绑定,但我收到以下错误:
其他信息:无法将当前JSON对象(例如{" name":" value"})反序列化为类型' WinFormVB.Documenti []'因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。
这是我的winform代码,用于访问API并使用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
这是我的存储库:
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;
}
}
}
请建议我如何解决此错误。感谢。
答案 0 :(得分:3)
您的JSON代表单个对象,而您的代码正在尝试反序列化为数组。那不行。
更改此行:
GridCtrlDocumenti.DataSource = JsonConvert.DeserializeObject(Of Documenti())(DocumentisonData).ToList()
对此:
Dim list As List(Of Documenti) = New List(Of Documenti)
list.Add(JsonConvert.DeserializeObject(Of Documenti)(DocumentisonData))
GridCtrlDocumenti.DataSource = list