I am using a library that return a IList<dynamic>
(from a jsonArray), dynamic
means not having any intellisense while using such object, I would like to be able to simply define what the dynamic object contains.
Asked
Active
Viewed 301 times
-1
-
7Don't use `dynamic`, then – canton7 Jul 27 '20 at 14:10
-
3What's your reason for using `dynamic` if you're aware of what the object contains? – msmolcic Jul 27 '20 at 14:11
-
can you cast each item to the interface-type? `myList.Cast
()` – MakePeaceGreatAgain Jul 27 '20 at 14:12 -
@msmolcic How can i not use dynamic ? that is what the method returns: `A Task whose result is the JSON response body deserialized to a list of dynamics.` – reonZ Jul 27 '20 at 14:22
-
@HimBromBeere i tried but i obviously am doing something wrong, i get `Unable to cast object of type 'System.Dynamic.ExpandoObject' to type ..` – reonZ Jul 27 '20 at 14:25
-
how do you deserialize the JSON? – MakePeaceGreatAgain Jul 27 '20 at 14:31
-
@HimBromBeere I am not, it is not my code, from what i can gather, the library (`Flurl`) uses `NewtonsoftJsonSerializer.Deserialize
(stream)` – reonZ Jul 27 '20 at 14:35 -
@HimBromBeere ok i think i found out, i was able to provide my own class for the deserialization using another method of the library, i guess snooping around the code trying to answer you helped (reading other's code is not my forte). – reonZ Jul 27 '20 at 14:45
1 Answers
1
Let's say you're calling some https://dummy-url.com/something
endpoint which returns the following JSON:
[
{
"firstProp": "First value",
"secondProp": "Second value",
"intProp": 1337
},
{
"firstProp": "Another first value",
"secondProp": "Another second value",
"intProp": 42
}
]
You would then need to define a class in your program representing that JSON structure, such as:
public class Something
{
public string FirstProp { get; set; }
public string SecondProp { get; set; }
public int IntProp { get; set; }
}
Finally, call that endpoint and deserialize its result to the object defined by your class:
public async IList<Something> FetchListOfSomething()
{
var url = "https://dummy-url.com/something";
return await url.GetJsonAsync<List<Something>>();
}

msmolcic
- 6,407
- 8
- 32
- 56
-
Yes that is what i did, found out i could provide `GetJsonAsync` with a paramter for the deserialization, i was originally using `GetJsonListAsync`. – reonZ Jul 27 '20 at 14:55