【问题标题】:WebAPI - Serializing an interface on complex class but still allowing concrete class to be serialized normallyWebAPI - 序列化复杂类的接口,但仍允许具体类正常序列化
【发布时间】:2014-01-28 05:28:07
【问题描述】:

我希望能够使用 Microsoft ASP.NET Web API 构建解决方案。我希望能够有一个复杂的对象,比如下面的“Person”,它实现了一个接口“IDisplayInfo”。当Person被序列化时,我希望所有属性都能正常序列化,但是当另一个像WorkOrder对象这样只指定接口的对象被序列化时,我希望只有接口上的属性被序列化。我希望它同时适用于 XML 和 JSON。我尝试覆盖 DefaultContractResolver,但我无法理解它是如何工作的。

感谢您的帮助!

public interface IDisplayInfo
{
    string Id { get; }
    string Display { get; }

}

public class Person : IDisplayInfo
{
    public string Id { get; set; }
    public string Display { get { return FirstName + " " + LastName; } }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class WorkOrder
{
    public string Title { get; set; }
    public IDisplayInfo CreatedBy { get; set; }
}

序列化的 WorkOrder 应如下所示: { 标题:“测试”,创建者:{ ID:“1”,显示:“Bob Fox”} }

序列化的人应该是这样的: { ID:“1”,显示:“Bob Fox”,名字:“Bob”,姓氏:“Fox”}

【问题讨论】:

  • 我在答案顶部添加了一个可能很有趣的链接。看看你能不能完成你需要的。

标签: c# asp.net json asp.net-web-api nsjsonserialization


【解决方案1】:

有一个你可能想要使用的属性:

NotSerialized

这告诉序列化程序跳过该属性。


你不能那样做。序列化基于具体数据,而不是像接口那样基于抽象。

看这里:Why can XmlSerializer serialize abstract classes but not interfaces?

或者这个:XmlSerialization with Interfaces

也就是说,您的解决方案可能是一个特殊的单独类型(此时它也可能是一个 struct),它有一个构造函数接收您的类并复制值。然后你可以序列化它:

public struct WorkOrderConcretized
{
    public string Title { get; set; }
    public PersonConcretized CreatedBy { get; set; }

    public WorkOrderConcretized(WorkOrder w)
    {
        this.Title = w.Title;
        this.CreatedBy = new PersonConcretized(w.CreatedBy);
    }
}

显然,PersonConcretized 结构必须采取相应措施。

反序列化将是另一个故事......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多