Search code examples
c#xml-serializationdatacontractserializer

DataContractSerializer stuck on WriteObject


I have objects (woah!) which can serialise themselves using a Serialise method. I've tried multiple serialise methods, but all have been stuck on the serialize.WriteObject method.

This is what my latest try looks like:

public string Serialise()
{
    DataContractSerializer serializer = new DataContractSerializer(this.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, this);
    ms.Position = 0;

    string serializedContent;
    using(StreamReader sr = new StreamReader(ms))
    {
        serializedContent = sr.ReadToEnd();   
    }
    return serializedContent;
}

I used to do this with a XmlSerializer and those didn't give me any trouble. I'm pretty sure I made my properties a DataMember and set up de DataContract of the class.

What am I doing wrong here? Is it the way I want to use this Serialisation? Is it because I want to serialise inside the class with the DataContract? I'm baffled..

------EDIT---------

Ugh.. I figured out what the problem was... My BaseObject had no DataContract and no DataMembers on their properties (although i would not want any of those properties in my xml). So apparently making only a DataContract for the extended class is not enough to serialise it.


Solution

  • Well you can try out this one

            using (var ms = new MemoryStream())
            {
                try
                {
                    string xml = string.Empty;
                    var dcs = new DataContractSerializer(this.GetType());
    
                    using (var xmlTextWriter = new XmlTextWriter(ms, Encoding.Default))
                    {
                        xmlTextWriter.Formatting = Formatting.Indented;
                        dcs.WriteObject(xmlTextWriter, this);
                        xmlTextWriter.Flush();
                        var item = (MemoryStream)xmlTextWriter.BaseStream;
                        item.Flush();
                        xml = new UTF8Encoding().GetString(item.ToArray());
                    }
                }
                finally
                {
                    ms.Close();
                }
            }
    
            return xml;