Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MyProject.HRDashboardViewModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'DashboardViewModel', line 1, position 16.
My json code
{"HRDashboard ":[{"Email":"[email protected]","FullName":"Bipin Dhakal","Location":"Taplejung Meringden Rural Municipality Tole Demo-01","JoinDate":"2007-01-25T00:00:00","Contact":646,"ImagePath":"\/Content\/images\/20160107_123742.jpg","Department":"Administration","StaffType":"Teacher"}]}
This is my view model
public class HRDashboardViewModel { public string Email { get; set; } public string Location { get; set; } public int Age { get; set; } public DateTime JoinDate { get; set; } public string Contact { get; set; } public string FullName { get; set; } public string ImagePath { get; set; } public string Deparment { get; set; } public string StaffType { get; set; } public int TotalPeriod { get; set; } public int TotalClass { get; set; } public int PendingTask { get; set; } public int ComplateTask { get; set; } public int TotalNotification { get; set; } public HRDashboardViewModel HRDashboard { get; set;}
}
My service
string report= ds.Tables[0].Rows[0].ItemArray[0].ToString(); var data = new HRDashboardViewModel(); if (!string.IsNullOrWhiteSpace(report)) { data = JsonConvert.DeserializeObject<HRDashboardViewModel>(report); } else { data = new HRDashboardViewModel(); }
Solutions
Solution: 1
Comment this this line from your HRDashboardViewModel class
//public HRDashboardViewModel HRDashboard { get; set;}
Add New proparties in your viewmodel class as give below
public List<HRDashboardViewModel> HRDashboard { get; set;}
It's working fine.you can see this image which is solved the issue.

Note:
JSON Array is not parse viewmodel object.JSON array want to convert viewmodel list and parse the JSON to your viewmodel.
If you want to convert object you should make sure to object type JSON.
Solution: 2
You can use this type of method as give below
var report= (HRDashboardViewModel)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(HRDashboardViewModel));
return report.data.Count.ToString();
Solution: 3
Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :
var report=JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
Comments