简体   繁体   中英

Deserialization of list of complex objects to exact list of Type

is there any way to deserialize a list of complex objects to a list of know type: 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; }
    }

this is the object on which i would like to deserialize to.

this is how i tried :

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);

but i get this exception

 "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.",

The inner exception:

"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)"
  }

Thank you.

so in order to deserialize to List i had to reference System.Web.Script.Serialization.

Create the correct object.

 public class MyType
    {
        public string Prop1Name{ get; set; }
        public string Prop2Name{ get; set; }
        public string PropNName{ get; set; }
    }

and use the JavaScriptSerializer from the namespace.

List<MyType> x = new JavaScriptSerializer().Deserialize<List<MyType>>(_content);

thank you Janis S

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM