I have problems with json deserialization , below is my json
{
"_id" : ObjectId("56bc28c436b252c406a67f17"),
"empname": "dhiraj",
"empcode": "123a",
"level": {
"levelID": 3,
"levelDescription": "manager",
"levelCode": "mg"
},
"Address": [
{
"Home": {
"streetname": "Home",
"city": "bbb",
"state": "aaa"
}
},
{
"Office": {
"streetname": "ofc",
"city": "ccc",
"state": "ddd"
}
}
]
}
And for above json the object classes are like
public class Employee
{
public ObjectId _id { get; private set; }
public string empname { get; set; }
public string empcode { get; set; }
public List<Level> level { get; set; }
public List<Address> Address { get; set; }
}
public class level
{
public string levelID { get; set; }
public string levelDescription { get; set; }
public string levelCode { get; set; }
}
public class Address
{
public List<Home> Home { get; set; }
public List<office> Office { get; set; }
}
public class Home
{
public string streetname { get; set; }
public string city { get; set; }
public string state { get; set; }
}
public class office
{
public string streetname { get; set; }
public string city { get; set; }
public string state { get; set; }
}
i tried to deserialize it using below code
Employee empobj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Employee>>(jsonData);
but got an error as
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
How can i fix it? Is there any way, the json result is from mongodb c# query.
List<Employee>- it's not an array at all. It's a singleEmployee. So useDeserializeObject<Employee>. Heck, I wouldn't expect the code you've given to even compile, given that you're assigning it to anEmployeevariable...[at the start and a]at the end, I suspect it'll work fine... but there's a huge difference between "an array with one element" and "one element".ObjectIdpart of your JSON is - that part is invalid JSON, basically.