Convert type 'System.Dynamic.DynamicObject to System.Collections.IEnumerable
Asked Answered
S

2

10

I'm successfully using the JavaScriptSerializer in MVC3 to de-serialize a json string in to a dynamic object. 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?

 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"))
Studhorse answered 27/11, 2012 at 20:0 Comment(2)
Cast it first to IDictionary<string, object>.Debit
Could you please post the layout of the json?Moxie
D
3

DynamicObject is inherited from IDictionary, so you can cast it to 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"))
Diplomatics answered 29/11, 2012 at 20:50 Comment(0)
S
7

Given your example usage of 'GetEntities', try changing its return type to IEnumerable<T> (or, although strongly not recommended, at least an IEnumerable<dynamic>). You would need to do some filtering within the method to extract the appropriate entities based on the 'entityName' input parameter. Although, it's unclear what the intended usage is of the other input parameter ('entityField').

Second answered 29/11, 2012 at 10:55 Comment(0)
D
3

DynamicObject is inherited from IDictionary, so you can cast it to 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"))
Diplomatics answered 29/11, 2012 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.