【问题标题】:Add some sort of interface to a Dynamic.ExpandoObject object向 Dynamic.ExpandoObject 对象添加某种接口
【发布时间】:2020-07-27 14:09:53
【问题描述】:

我正在使用一个返回 IList<dynamic>(来自 jsonArray)的库,dynamic 表示在使用此类对象时没有任何智能感知,我希望能够简单地定义动态对象包含的内容。

【问题讨论】:

  • 不要使用dynamic,那么
  • 如果您知道对象包含什么,您使用dynamic 的原因是什么?
  • 你能把每个项目都转换成接口类型吗? myList.Cast<InterfaceType>()
  • @msmolcic 我怎么能不使用动态?这就是方法返回的内容:A Task whose result is the JSON response body deserialized to a list of dynamics.
  • @HimBromBeere 我试过了,但显然我做错了什么,我得到了Unable to cast object of type 'System.Dynamic.ExpandoObject' to type ..

标签: c# .net expandoobject flurl


【解决方案1】:

假设您正在调用某个返回以下 JSON 的 https://dummy-url.com/something 端点:

[
    {
        "firstProp": "First value",
        "secondProp": "Second value",
        "intProp": 1337
    },
    {
        "firstProp": "Another first value",
        "secondProp": "Another second value",
        "intProp": 42
    }
]

然后,您需要在程序中定义一个表示该 JSON 结构的类,例如:

public class Something
{
    public string FirstProp { get; set; }
    public string SecondProp { get; set; }
    public int IntProp { get; set; }
}

最后,调用该端点并将其结果反序列化为您的类定义的对象:

public async IList<Something> FetchListOfSomething()
{
    var url = "https://dummy-url.com/something";
    return await url.GetJsonAsync<List<Something>>();
}

【讨论】:

  • 是的,我就是这么做的,发现我可以为GetJsonAsync 提供反序列化的参数,我最初使用的是GetJsonListAsync
猜你喜欢
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多