[英]Convert type 'System.Dynamic.DynamicObject to System.Collections.IEnumerable
I'm successfully using the JavaScriptSerializer in MVC3 to de-serialize a json string in to a dynamic object. 我成功地使用MVC3中的JavaScriptSerializer将json字符串反序列化为动态对象。 What I can't figure out is how to cast it to something I can enumerate over. 我无法弄清楚的是如何将它投射到我可以列举的东西上。 The foreach line of code below is my latest attemt but it errors with: "Cannot implicitly convert type 'System.Dynamic.DynamicObject' to 'System.Collections.IEnumerable'. How can I convert or cast so that I can iterate through the dictionary? 下面的foreach代码行是我最新的attemt,但它错误:“无法将类型'System.Dynamic.DynamicObject'隐式转换为'System.Collections.IEnumerable'。如何转换或转换以便我可以遍历字典?
public dynamic GetEntities(string entityName, string entityField)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new MyProject.Extensions.JsonExtension.DynamicJsonConverter() });
dynamic data = serializer.Deserialize(json, typeof(object));
return data;
}
foreach (var author in GetEntities("author", "lastname"))
Given your example usage of 'GetEntities', try changing its return type to IEnumerable<T>
(or, although strongly not recommended, at least an IEnumerable<dynamic>
). 鉴于您使用'GetEntities'的示例,请尝试将其返回类型更改为IEnumerable<T>
(或者,尽管强烈建议不要使用,但至少要使用IEnumerable<dynamic>
)。 You would need to do some filtering within the method to extract the appropriate entities based on the 'entityName' input parameter. 您需要在方法中进行一些过滤,以根据'entityName'输入参数提取适当的实体。 Although, it's unclear what the intended usage is of the other input parameter ('entityField'). 虽然,目前还不清楚其他输入参数('entityField')的用途是什么。
DynamicObject is inherited from IDictionary, so you can cast it to IDictionary. DynamicObject继承自IDictionary,因此您可以将其强制转换为IDictionary。
public IDictionary<string, object> GetEntities(string entityName, string entityField)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new MyProject.Extensions.JsonExtension.DynamicJsonConverter() });
dynamic data = serializer.Deserialize(json, typeof(object));
return data as IDictionary<string, object>;
}
foreach (var author in GetEntities("author", "lastname"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.