2

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)));
slartidan
  • 20,403
  • 15
  • 83
  • 131
  • As I know WCF uses its own custom serialization mechanisms, so `ISerializable` interface is not the solution that will handle custom serialization-deserialization. You may want to read http://stackoverflow.com/questions/8084868/how-to-use-custom-serialization-or-deserialization-in-wcf-to-force-a-new-instanc and http://stackoverflow.com/questions/9791056/how-to-customize-data-serialization-based-on-content-in-wcf – Eugene Podskal Jul 16 '14 at 17:24
  • The default mechanism (DataContract) works fine for my other services, but in this case I need custom serialization. Everything worked fine, until I added the parent/child relationship. – slartidan Jul 16 '14 at 17:37

0 Answers0