开发者

Why does DataContractSerializer Generate a node with the name : "z:anytype"?

When working with the DataContractSerializer I am getting alot of extra attributes for namespaces that I dont really开发者_JAVA技巧 want to work with. I have generated a similar data structure in a different project without all the extra markup so I know its possible.

Why does DataContractSerializer Generate a node with the name : "z:anytype" ?


My problem was that I was passing an interface as a type to my DataContractSerializer.

It was easy to miss because my interface was named IInvestment.

If you ever have this issue check the type that you are passing to the DataContractSerializer Constructor.


You'll have that if you're serializing some collection (array, list, dictionary, etc) of object - anyType really means that any type could be there (although you have an attribute specifying the actual type for the value). In the example below it shows that.

public class StackOverflow_6780831
{
    [DataContract(Name = "Order")]
    public class Order
    {
        [DataMember(Order = 1)]
        public int Id;
        [DataMember(Order = 2)]
        public List<object> List;
    }
    public static void Test()
    {
        MemoryStream ms = new MemoryStream();
        Order order = new Order
        {
            Id = 1,
            List = new List<object>
            {
                1, "some string", DateTime.Now
            },
        };
        DataContractSerializer dcs = new DataContractSerializer(typeof(Order));
        XmlWriter w = XmlWriter.Create(ms, new XmlWriterSettings
        {
            Indent = true,
            IndentChars = "  ",
            OmitXmlDeclaration = true
        });
        dcs.WriteObject(w, order);
        w.Flush();
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜