Question

I would like to be able to build a solution using Microsoft ASP.NET Web API. I would like to be able able to have a complex object like 'Person' below which implements an interface 'IDisplayInfo'. When the Person is serialized, I would like all properties to be serialized normally, but when another object that only specifies the interface like the WorkOrder object is serialized, I would like only the properties on the interface to be serialized. I would like it to work with both XML and JSON. I tried overriding the DefaultContractResolver, but I'm having trouble understanding how this works.

Thank you for your help!

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; }
}

Serialized WorkOrder should look like this: { Title: "test", CreatedBy: { Id: "1", Display: "Bob Fox" } }

Serialized Person should look like this: { Id: "1", Display: "Bob Fox", FirstName: "Bob", LastName: "Fox" }

Was it helpful?

Solution

There is an attribute you might want to use:

NotSerialized

This tells the serializer to skip that property.


You cannot do that. Serialization is based on concrete data, not on abstractions as is an interface.

Look here: Why can XmlSerializer serialize abstract classes but not interfaces?

Or this: XmlSerialization with Interfaces

That said, your solution might be a special separate type (at this point it might as well be a struct) that has a constructor taking in your class and copying the values. You can then serialize that:

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

Obviously, the PersonConcretized struct will have to act accordingly.

Deserialization will be another story...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top