无法将类型 'Newtonsoft.Json.Linq.JObject' 隐式转换为 'System.Collections.Generic.IEnumerable<Employee>'

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

我有以下代码:

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

其中 EmployeeRecords 的类型为 IEnumerable<Employee>

我遇到以下异常:

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

我该如何解决这个问题?

嗯,您正在尝试将单个员工分配给可枚举对象。尝试:

filteredEmployees.EmployeeRecords = employee; 

你在那个方法上使用动态参数有什么好的理由吗?

如果您只想在枚举中使用一个元素,您可以尝试:

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

尽管我怀疑您有时需要将 JSON 对象反序列化为 Employee 对象

您可以使用 JavascriptSerializer 将动态转换为员工:

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

该消息表明 employee[0] 作为 JObject 返回,因此必须对其进行解析才能转换为另一种类型的对象。我还没有看到足够多的代码来知道哪一个最适合你,你可能需要采取更多步骤,但是像动态到强类型映射(使用 JObject.ToObject())或强类型 JSON 如下页所述的解析(使用 JsonConvert.DeserializeObject())应该会让您走上正确的道路:

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