我遇到了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#query。
答案 0 :(得分:2)
这里有几个问题:
level
的类,但将其用作Level
List<Employee>
,但您的JSON仅指定一个Employee
对象;这与包含单个对象的对象数组不同ObjectId("56bc28c436b252c406a67f17")
根本不是JSON中的有效值。可能是Json.NET对这种奇怪性有一些支持,但如果你能使用有效的JSON会更好Address
类为List<Home>
属性指定Home
,同样为Office
属性指定,但JSON再次指定对象值,而不是数组。同样适用于level
属性。此外,你有Home
和Office
的单独类这一事实是非常令人讨厌的,因为命名约定的混合。地址的JSON结构远非理想,但我想你无法解决这个问题。
我无法解决ObjectId
问题,但我将这些类构建为:
public class Employee
{
[JsonProperty("_id")]
public ObjectId Id { get; private set; }
[JsonProperty("empname")]
public string Name { get; set; }
[JsonProperty("empcode")]
public string Code { get; set; }
[JsonProperty("level")]
public Level Level { get; set; }
[JsonProperty("Address")]
public List<Address> Addresses { get; set; }
}
public class Level
{
[JsonProperty("levelID")]
public string Id { get; set; }
[JsonProperty("levelDescription")]
public string Description { get; set; }
[JsonProperty("levelCode")]
public string Code { get; set; }
}
// This structure is unfortunate, but imposed by the JSON
public class Address
{
[JsonProperty("Home")]
public StreetAddress Home { get; set; }
[JsonProperty("Office")]
public StreetAddress Office { get; set; }
}
public class StreetAddress
{
[JsonProperty("streetname")]
public string StreetName { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("state")]
public string State { get; set; }
}
除ObjectId
之外,它将解析您使用的JSON:
var employee = JsonConvert.DeserializeObject<Employee>(json);