我有JSON反序列化的问题,以下是我的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"
}
}
]
}
对于上述JSON,对象类别如下:
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; }
}
我尝试使用以下代码进行反序列化
Employee empobj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Employee>>(jsonData);
但是遇到了以下错误:
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.
如何解决这个问题?这个json结果是来自于mongodb c#查询的吗?
List<Employee>
- 它根本就不是一个数组。它只是一个单独的Employee
对象。所以使用DeserializeObject<Employee>
来解析它。天哪,考虑到你将其赋值给一个Employee
变量,我甚至不指望你给出的代码能够编译通过... - Jon Skeet[
和结尾处添加一个]
,我认为它会正常工作...但是“一个元素的数组”和“一个元素”之间存在着巨大的区别。 - Jon SkeetObjectId
部分的JSON无效,不够清晰。 - Jon Skeet