Persisting object values between XML serialization and deserialization (C #)
I have a class that I am trying to serialize and deserialize using XMLSerializer. This 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 am aware of the XMLSerialization issue with classes that do not have empty constructor parameters, which I encountered when creating a private default constructor. This is 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 the values (4, 8), but instead display (0, 0). I need to be able to preserve the values of objects during serialization, preferably while preserving XML serialization.
source to share
Your data is not serialized because it is stored in private fields. Only public members are serialized. As mentioned in the comments, you are a Java developer, so you need to take a look at properties . Using them, your model might look like this:
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;
}
source to share