I'm currently working on a .NET Framework 4.7.2 application. I'm retrieving data from a Web API as a JSON string result, I need to convert the result into an IEnumerable or IList of ExpandoObject.
my JSON can have dynamic properties and looks like this:
{ "data" : [
{"Id":1, Text:"Test1", coolProp: 213 },
{"Id":2, Text:"Test2"},
{"Id":3, Text:"Test3", otherProp: "cool" },
]}
I need to select the JSON objects, without the key "data" and return a dynamic List of ExpandoObjects.
My current C# looks like this:
var json = JsonConvert.DeserializeObject<ExpandoObject>(await response.Content.ReadAsStringAsync());
var result = json.FirstOrDefault(x => x.Key == "data").Value;
This works fine, but the result is just a simple object containing several ExpandoObjects.
I can not cast the result, neither implicitly nor explicitly, to a List<ExpandoObject>
.
When I try to return result, the Error message is the following:
Cannot implicitly convert type 'object' to List.
When I try to cast explicitly, result is null:
var result= json.FirstOrDefault(x => x.Key == "data").Value as List<IDictionary<int, ExpandoObject>>;
The result without cast looks like that in the immediate window:
result
Count = 7
[0]: {System.Dynamic.ExpandoObject}
[1]: {System.Dynamic.ExpandoObject}
[2]: {System.Dynamic.ExpandoObject}
[3]: {System.Dynamic.ExpandoObject}
[4]: {System.Dynamic.ExpandoObject}
[5]: {System.Dynamic.ExpandoObject}
[6]: {System.Dynamic.ExpandoObject}
Do you know how to solve this issue? Or perhaps, do you know a better approach? I don't want to return the key "data" in my result, just a simple list of dynamic objects.
Thank you!!