I need to store list objects which implements IAnimal interface to Windows Phone 8 IsolatedStorageSettings.ApplicationSettings.
My animal interface looks like this:
public interface IAnimal
{
string Name { get; }
}
Then I have different animals which I want to store to IsolatedStorageSettings.ApplicationSettings.
public class Cat : IAnimal
{
string Name { get; set; }
}
public class Dog: IAnimal
{
string Name { get; set; }
}
I have methods to get / set list of animals.
public IReadOnlyCollection<IAnimal> GetAnimals()
{
return (List<IAnimal>)storage["animals"];
}
public void AddAnimal(IAnimal animal)
{
List<IAnimal> animals = (List<IAnimal>)storage["animals"];
animals.Insert(0, (IAnimal)animal);
this.storage["animals"] = animals;
this.storage.Save();
}
If I use these methods, I will get System.Runtime.Serialization.SerializationException, Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:anyType' contains data of the 'http://schemas.datacontract.org/2004/07/MyApp.Models:Cat' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'Cat' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.
I have also tried to add KnownType attribute to Cat and Dog but with out success.
Is this the proper way to store object to IsolatedStorageSettings, when I know only that the object implements certain interface?
I would suspect you are placing the KnownType attribute in the wrong place. When I have used it, I have always added it to a base class.
Example:
public interface IAnimal
{
string Name { get; }
}
[KnownType(typeof(Cat))]
[KnownType(typeof(Dog))]
public class Animal: IAnimal
{
string Name { get; }
}
public class Cat : Animal
{
string Name { get; set; }
}
public class Dog: Animal
{
string Name { get; set; }
}
http://msdn.microsoft.com/en-us/library/ms751512(v=vs.110).aspx