Cannot implicitly convert type 'Newtonsoft.Json.Linq.JObject' to 'System.Collections.Generic.IEnumerable<Employee>'

為{幸葍}努か 提交于 2021-02-10 11:44:06

问题


I have the following code:

public EmployeeDepartment InsertEmployeeAndDepartment(params dynamic[] employee)
{                
    filteredEmployees.EmployeeRecords = employee[0];           
}

Where EmployeeRecords is of type IEnumerable<Employee>

I am getting the following exception:

Cannot implicitly convert type 'Newtonsoft.Json.Linq.JObject' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

How can I resolve this?


回答1:


The message suggests that employee[0] is being returned as a JObject, so it has to be parsed in order to be cast to another type of object. I haven't seen enough of your code to know which one will work best for you, and you may have more steps to take, but something like the Dynamic to Strong Type Mapping (using JObject.ToObject()) or Strongly Typed JSON Parsing (using JsonConvert.DeserializeObject()) as described on the following page should put you on the right path:

http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing#DynamictoStrongTypeMapping




回答2:


You can use JavascriptSerializer to convert your dynamic into Employee :

public EmployeeDepartment InsertEmployeeAndDepartment(params dynamic[] employee)
{         
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();       
    filteredEmployees.EmployeeRecords = serializer.Deserialize<List<EmployeeRecords >>(employee);           
}



回答3:


Uhm you are trying to assing a single employee to an enumerable. Try:

filteredEmployees.EmployeeRecords = employee; 

Is there any good reason why you are using a dynamic parameter on that method?

If you want just one element in your enumerable you can try:

filteredEmployees.EmployeeRecords = new [] { employee[0] }; 

Although I suspect you will need at some point to deserialize the JSON object into a Employee object



来源:https://stackoverflow.com/questions/29541415/cannot-implicitly-convert-type-newtonsoft-json-linq-jobject-to-system-collect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!