I want to implement serialization in c#.net for an object of class B that can contain an object of class A. But everytime I call info.AddValue("Value", a, a.GetType());
my wcf webservice is not able to process the request anymore.
How do I do custom serialization for parent/child classes?
PS: DataContract
is not an option for me, because I need to optimize the JSON later on
My example code:
[Serializable]
public class A : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
}
}
[Serializable]
public class B : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
A a = new A();
object o = new object();
// does not work
info.AddValue("Value", a, a.GetType());
// does not work
// info.AddValue("Value", a);
// works and returns {"Value":{}}
// info.AddValue("Value", o, o.GetType());
// works and returns {"Value":{}}
// info.AddValue("Value", o);
// works and returns {"Value":{}}
// info.AddValue("Value", o, typeof(A));
// runs but returns {"Value":"{}"}
// MemoryStream stream1 = new MemoryStream();
// new DataContractJsonSerializer(typeof(A)).WriteObject(stream1, a);
// stream1.Position = 0;
// StreamReader sr = new StreamReader(stream1);
// info.AddValue("Value", sr.ReadToEnd(), typeof(A));
}
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
[ServiceContract]
public class BService
{
[OperationContract]
[WebGet]
public B getB()
{
return new B();
}
}
And in Global.cs
I added the following code to Application_Start
:
RouteTable.Routes.Add(new ServiceRoute("BService", new WebServiceHostFactory(), typeof(BService)));