Search code examples
c#.netexpandoobjectflurl

Add some sort of interface to a Dynamic.ExpandoObject object


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.


Solution

  • 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>>();
    }