有没有办法将复杂对象列表反序列化为已知类型列表: EX:
public class Employee
{
public string EmployeeNumber { get; set; }
public string AccountName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PreferredName { get; set; }
public string Title { get; set; }
}
这是我想要反序列化的对象。
这就是我的尝试方式 :
var x = JsonConvert.DeserializeObject<List<Dictionary<string, IList<Employee>>>>(_content);
var x = JsonConvert.DeserializeObject<List<Dictionary<string, Employee>>>(_content);
var x = JsonConvert.DeserializeObject<List<Dictionary<string, Employee[]>>>(_content);
但是我得到了这个例外
"ExceptionMessage": "Error converting value 37326 to type 'System.Collections.Generic.IList`1[Ubisoft.ECM.Events.Business.Providers.EmployeeProvider.Empoyee]'. Path '[0].EmployeeNumber', line 1, position 24.",
内部异常:
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Could not cast or convert from System.Int64 to System.Collections.Generic.IList`1[Ubisoft.ECM.Events.Business.Providers.EmployeeProvider.Employee].",
"ExceptionType": "System.ArgumentException",
"StackTrace": " at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)\r\n at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)"
}
谢谢。
答案 0 :(得分:1)
所以为了反序列化到List我必须引用System.Web.Script.Serialization。
创建正确的对象。
public class MyType
{
public string Prop1Name{ get; set; }
public string Prop2Name{ get; set; }
public string PropNName{ get; set; }
}
并使用命名空间中的JavaScriptSerializer。
List<MyType> x = new JavaScriptSerializer().Deserialize<List<MyType>>(_content);
谢谢Janis S