开发者

How to ensure that the serialization and deserialization with WebServices is symmetric?

I have a couple of standard ASP.NET web methods that I'm calling from javascript with a parameter that is of a custom class in form

[DataContract]
[KnownType(typeof(MyOtherSubclass))]
public class MyClass
{
     [DataMember]
     public MyOtherClass MyMember { get; set; }
}

where MyOtherClass is a class marked with Serializable but not with DataContract attribute (I don't have a control over its generation). There is a couple of subclasses of MyOtherClass, e.g. MyOtherSubclass :

[Serializable]
public class MyOtherSubClass : MyOtherClass
{
    private string valueField;
    public string Value 
    {
        get { return valueField; }
        set { valueField = value; }
    }
}

When I use the DataContractJsonSerializer to serialize an object of MyClass directly, I get a result similar to

{ "MyMember" : { "__type" : "MyOtherSubClass:#Namespace", "valueField" : "xxx" } }

However, when 开发者_JAVA百科I pass such a JSON into the web method request from javascript, I get an exception while deserializing. I have experimented a little bit and found that when using the following one instead

{ "MyMember" : { "___type" : "Namespace.MyOtherSubClass", "Value" : "xxx" } }

the deserialization works without any problems.

Is there any way to configure the DataContractJsonSerializer in such a way that it would produce the JSON in the second form, so that the web method arguments deserialization would work ?


ASP.NET WebMethods use JavaScriptSerializer, so try serializing with it. You might need a custom type resolver in order to include this property:

public class Parent
{
    public string ParentProp { get; set; }
}

public class Child: Parent
{
    public string ChildProp { get; set; }
}

public class CustomResolver : JavaScriptTypeResolver
{
    public override Type ResolveType(string id)
    {
        return Type.GetType(id);
    }

    public override string ResolveTypeId(Type type)
    {
        return type.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var o = new Child
        {
            ParentProp = "parent prop",
            ChildProp = "child prop",
        };

        var serializer = new JavaScriptSerializer(new CustomResolver());
        var s = serializer.Serialize(o);
        Console.WriteLine(s);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜