Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASMX Web service not serializing abstract base class

I have an abstract class. Let's call it Lifeform. It looks something like:

public abstract class Lifeform {
    public virtual int Legs { get; set; }
    public virtual int Arms { get; set; }
    public virtual bool Alive { get; set; }
}

(The virtual attribute is due to the fact that I'm using nHibernate, which whines if they're not virtual properties.)

I then have a class which inherits from that Lifeform class; we'll call it Human. It looks something like:

public class Human: Lifeform {
    public virtual bool Hat { get; set; }
    public virtual int Age { get; set; }
    public virtual string Name { get; set; }
}

Everything's lovely, I can use my classes, Human gets the Legs, Arms, and Alive properties when I'm using it. Except, that is, when I attempt to make a web service using the Human class. The serialized object gives me Hat, Age, and Name - but no Legs, Arms, or Alive properties.

I've seen a workaround that suggests using

[System.Xml.Serialization.XmlInclude(typeof(Human))]

On the base class (Lifeform), but that seems like a horrible hack that violates OO. Putting links on the base class to the classes that inherit it? Eww.

Has anyone run into this specific issue before? Have any ideas? I'll provide more code if a more in-depth example would help describe what I'm doing more.

like image 970
Jack Lawson Avatar asked Aug 11 '09 18:08

Jack Lawson


1 Answers

From what I've read, you can include the XMLInclude attribute on the web method returning the object rather than in the base class. Still not pretty, but might appeal to you a little more than putting derived class names in the base class. I haven't tried it out, but I think you can do something like this.

[WebMethod]
[XmlInclude(typeof(LifeForm))]
public Human GetHuman()
{
   return new Human();
}
like image 165
Sterno Avatar answered Sep 29 '22 10:09

Sterno