Nick Gilbert
Nick Gilbert

Reputation: 4240

Keeping object values between XML Serialization and Deserialization (C#)

I have a class that I'm trying to serialize and deserialize with an XMLSerializer. That class looks like this:

namespace AutoCAD_Adapter
{
    /// <summary>
    /// Test class meant to be serialized to test serialization methods
    /// </summary>
    [Serializable]
    public class SerializeTest// : ISerializable
    {
        #region class variables
        private int x;
        private int y;
        #endregion

        #region Constructors
        public SerializeTest(int passedX, int passedY)
        {
            this.x = passedX;
            this.y = passedY;
        }

        private SerializeTest()
        {

        }

        #endregion

        #region Public methods
        public void setX(int x)
        {
            this.x = x;
        }

        public int getX()
        {
            return this.x;
        }

        public void setY(int y)
        {
            this.y = y;
        }

        public int getY()
        {
            return this.y;
        }



        #endregion
    }
}

I'm aware of XMLSerialization's issue with classes that do not have empty constructor parameters which I've dealt with by creating a private default constructor. That noted, here is my implementation:

public void XMLSave()
{
    SerializeTest input = new SerializeTest(4, 8); //Object to serialize
    using (MemoryStream stream = new MemoryStream())
    {
        XmlSerializer serializer = new XmlSerializer(st.GetType());
        serializer.Serialize(stream, input);
        stream.Position = 0;
        SerializeTest output = serializer.Deserialize(stream) as SerializeTest;
        MessageBox.Show(output.getX() + " " + output.getY(), "Output", MessageBoxButtons.OK);
    }
}

Upon execution, I expect the MessageBox to show values of (4, 8) but instead it shows (0, 0). I need to be able to preserve object values throughout serialization, preferably while maintaining XML serialization.

Upvotes: 3

Views: 122

Answers (1)

Aleksandr Ivanov
Aleksandr Ivanov

Reputation: 2786

Your data is not serialized because it's hold by private fields. Only public members are serialized. As mentioned in comments you are Java developer, so you need to take a look at properties. Using them your model might look like that:

public class SerializeTest
{
    public int X { get; set; }
    public int Y { get; set; }

    public SerializeTest(int x, int y)
    {
        X = x;
        Y = y;
    }

    public SerializeTest()
    {
    }
}

Now you can easily serialize and deserialize it:

var input = new SerializeTest(4, 8);

using (var ms = new MemoryStream())
{
    var serializer = new XmlSerializer(typeof(SerializeTest));
    serializer.Serialize(ms, input);
    ms.Position = 0;

    var output = serializer.Deserialize(ms) as SerializeTest;
}

Upvotes: 3

Related Questions