您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

转换JSON.NET中反序列化的接口

转换JSON.NET中反序列化的接口

@SamualDavis在一个相关的问题中提供了一个很好的解决方案,我将在这里进行总结。

如果必须将JSON流反序列化为具有接口属性的具体类,则可以 将具体类作为参数包含在该类的构造函数中! NewtonSoft反序列化器足够聪明,可以弄清楚它需要使用那些具体的类来反序列化属性

这是一个例子:

public class Visit : IVisit
{
    /// <summary>
    /// This constructor is required for the JSON deserializer to be able
    /// to identify concrete classes to use when deserializing the interface properties.
    /// </summary>
    public Visit(MyLocation location, Guest guest)
    {
        Location = location;
        Guest = guest;
    }
    public long VisitId { get; set; }
    public ILocation Location { get;  set; }
    public DateTime VisitDate { get; set; }
    public IGuest Guest { get; set; }
}
dotnet 2022/1/1 18:15:24 有509人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶