问题
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