使用ISerializable接口序列化复杂类型

时间:2014-07-16 17:16:47

标签: c# wcf serialization

我想在c#.net中为包含A类对象的B类对象实现序列化。但每次调用info.AddValue("Value", a, a.GetType());时,我的wcf webservice都无法处理请求。

如何为父/子类进行自定义序列化?

PS:DataContract对我来说不是一个选项,因为我需要稍后优化JSON

我的示例代码:

[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();
    }
}

Global.cs中,我将以下代码添加到Application_Start

    RouteTable.Routes.Add(new ServiceRoute("BService", new WebServiceHostFactory(), typeof(BService)));

0 个答案:

没有答案