Search code examples
c#jsonwcf

WCF Return list of baseclass objects containing derived class


I've got a function returning all snakes. Looks like this and works fine:

// Function that returns JSON list of snakes
public List<Snake> GetSnakes()
{
    var snakes = new List<Snakes>();
    snakes.Add(new Snake { Length = "10.2" } );
    return snakes;
}

Now I got a bunch of animals with different properties, and I dont want to make a list for each one of them. I would like something like this:

public class AnimalService : IAnimalService
{
    private List<Animal> animals = new List<Animals>();

    public List<Animal> getSnakes()
    {
        animals.Add(new Snake { Name = "Snake" } );
        return animals;
    }

    public List<Animal> getPigs()
    {
        animals.Add( new Pig { Weight = "100" } );
        return animals;
    }
}

But this doesnt work. When I add a derived class to my animal list, the WCF service stops producing JSON for that function and returns nothing. No errors or anything but no results. How can I achieve what I want? One list containing return set of animals, doesn't matter what type.


Solution

  • Try adding a KnownTypeAttribute to your Animal class for each subclass you'd like to have serialized:

    [DataContract]
    [KnownType(typeof(Snake))]
    [KnownType(typeof(Pig))]
    public class Animal 
    {
    }