DataContract序列化异常(不期望数据协定名称)

时间:2011-02-02 13:48:06

标签: c# serialization reflection datacontract

我有以下代码:

[DataContract]
class TestContract {
    private String _Name;
    private Int32 _Age;

    [DataMember( Name = "Name" )]
    public String Name {
        get { return _Name; }
        set { _Name = value; }
    }

    [DataMember( Name = "Age" )]
    public Int32 Age {
        get { return _Age; }
        set { _Age = value; }
    }
}

[Serializable]
public class DNCJsonDictionary<K, V> : ISerializable {
    Dictionary<K, V> dict = new Dictionary<K, V>();

    public DNCJsonDictionary() { }

    protected DNCJsonDictionary( SerializationInfo info, StreamingContext context ) {
    }

    public void GetObjectData( SerializationInfo info, StreamingContext context ) {
        foreach( K key in dict.Keys ) {
            info.AddValue( key.ToString(), dict[ key ] );
        }
    }

    public void Add( K key, V value ) {
        dict.Add( key, value );
    }

    public V this[ K index ] {
        set { dict[ index ] = value; }
        get { return dict[ index ]; }
    }
}

public class MainClass {
    public static String Serialize( Object data ) {
        var serializer = new DataContractJsonSerializer( data.GetType() );
        var ms = new MemoryStream();
        serializer.WriteObject( ms, data );

        return Encoding.UTF8.GetString( ms.ToArray() );
    }

    public static void Main() {
        DNCJsonDictionary<String, Object> address = new DNCJsonDictionary<String, Object>();
        address[ "Street" ] = "30 Rockefeller Plaza";
        address[ "City" ] = "New York City";
        address[ "State" ] = "NY";

        TestContract test = new TestContract();
        test.Name = "CsDJ";
        test.Age = 28;

        DNCJsonDictionary<String, Object> result = new DNCJsonDictionary<String, Object>();
        result[ "foo" ] = "bar";
        result[ "Name" ] = "John Doe";
        result[ "Age" ] = 32;

        result[ "Address" ] = address;

            // ** --- THIS THROWS AN EXCEPTION!!! --- **            
        result[ "test" ] = test;

        Console.WriteLine( Serialize( result ) );

        Console.ReadLine();
    }
}

当我跑步时,我得到了这个例外:

  

不希望输入数据合约名称为“TestContract:http://schemas.datacontract.org/2004/07/Json_Dictionary_Test”的“Json_Dictionary_Test.TestContract”。将任何静态未知的类型添加到已知类型列表中 - 例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

但我不明白!据我所知,KnownTypeAttribute只用于反序列化,如果有继承,不是吗?但这里只是序列化。并且没有datacontract成员工作正常。

有什么想法吗?


我找到了有效的东西!有一个带有KnownTypes列表的父类,我将其填充所有子类,并将用于序列化:

[DataContract]
[KnownType( "GetKnownTypes" )]  // for serialization
class ResultContract {
    private static List<Type> KnownTypes { get; set; }

    public static List<Type> GetKnownTypes() {
        return KnownTypes;
    }

    static ResultContract() {
        KnownTypes = new List<Type>();
        try {
            foreach( Type type in Assembly.GetExecutingAssembly().GetTypes() ) {
                if( !type.IsAbstract && type.IsSubclassOf( typeof( ResultContract ) ) ) {
                    KnownTypes.Add( type );
                }
            }
        } catch( Exception ex ) {
            Console.WriteLine( "Fatal error!" );
        }
    }
}

[DataContract]
class TestContract : *ResultContract* {
    ...
}
...

1 个答案:

答案 0 :(得分:22)

添加以下行:

 [KnownType(typeof(TestContract))]

那样

[Serializable]
[KnownType(typeof(TestContract))]
public class DNCJsonDictionary<K, V> : ...

这是一个已知问题。这就是为什么泛型不能与WCF一起使用。

但原因很简单, WCF应该创建WSDL 并能够发布您的合同。使用泛型来定义你的契约是很好的,但是WSDL需要指向一些具体的类,因此你需要KnownType