用json.net解析嵌套的json
我有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 { get; set; } public List 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 { get; set; } public List 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>(jsonData);
但得到了一个错误
Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.
我该如何解决? 有没有办法,json结果来自mongodb c#query。
这里有几个问题:
- 您已经给出的代码将无法编译,因为您已经指定了一个名为
level
的类,但将其用作Level
- 您正在尝试反序列化
List
,但您的JSON仅指定一个Employee
对象; 这与包含单个对象的对象数组不同 - 您的JSON无效 –
ObjectId("56bc28c436b252c406a67f17")
在JSON中不是有效值。 可能是Json.NET对这种奇怪性有一些支持,但如果你能使用有效的JSON会更好 - 您的
Address
类为Home
属性指定List
,同样对于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 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(json);