I have two classes which inherits from an abstract class
public class Class1 : MainBaseClass
{
public int attrib1 {get; set;}
public int attrib2 {get; set;}
}
public class Class2 : MainBaseClass
{
public int attribx {get; set;}
public int attriby {get; set;}
}
Then I created a list of type MainBaseClass in order to serialize both classes in one JSON string but I got this exception
An exception of type 'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll but was not handled in user code
Additional information: Type 'MyProject.Class1' with data contract name 'Class1:http://schemas.datacontract.org/2004/07/MyProject' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
My method does this:
Class1 class1 = getData();
Class2 class2 = getData();
Package<MainBaseClass> package = new Package<MainBaseClass>();
package.AddObject(class1)
package.AddObject(class2);
//Here's the error
new ServiceClass().Serialize<Package<MainBaseClass>>(package);
My package class
public class Package<T>
{
public List<T> Objects = new List<T>();
public Package() { }
public void AddObject(T dto)
{
this.Objects.Add(dto);
}
}
My serializer method
public static string Serialize<T>(T entity)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
//Here's the exception
ser.WriteObject(stream, entity);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
return sr.ReadToEnd();
}
I also added [DataContract()] on the MainBaseClass and the child classes and the exception persists.
It only works if I do this, removing the [DataContract()] from the base class and the child classes previously. If not, I receive the results as an empty string "{}"
Class1 class1 = getData();
Package<Class1> package = new Package<Class1>();
package.AddObject(class1)
string str = new ServiceClass().Serialize<Package<Class>>(package);
Or this:
Class1 class1 = getData();
string str = new ServiceClass().Serialize<Class1>(class1);
So, how can I serialize multiple objects of different types?