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

25,266

Solution 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

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

Solution 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

Share:
25,266
priyanka.sarkar
Author by

priyanka.sarkar

Student

Updated on February 01, 2022

Comments

  • priyanka.sarkar
    priyanka.sarkar about 2 years

    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?

  • priyanka.sarkar
    priyanka.sarkar about 9 years
    "employee" an array ..i have to ultimately do filteredEmployees.EmployeeRecords = employee[0] and filteredEmployees.DeptRecords = employee[1];
  • JRodd
    JRodd almost 5 years
    I believe this is the correct answer. In my case I wanted to convert the JObject to a dynamic, then convert the dynamic to an IDictionary<string, object> so I could work with the names like obj["[Field Name]"]. I had to use JObject.ToObject<IDictionary<string, object>>(). Thanks for the suggestion.