samedi 9 mai 2015

How does marking classes as [Serializable] work in C#?

I made a class called MyData and marked it with [Serializable], but it doesn't seem to work...

Here's MyData.cs:

namespace Forms_Bot_Rebuild
{
    [Serializable]
    public class MyData
    {
        private String _Email;
        private String _Password;
        private String _WorldId;
        public MyData(string email, string password, string worldid)
        {
            _Email = email;
            _Password = password;
            _WorldId = worldid;
        }
        public string Email
        { get { return _Email; } set { _Email = value; } }
        public string Password
        { get { return _Password; } set { _Password = value; } }
        public string WorldId
        { get { return _WorldId; } set { _WorldId = value; } }
    }
}

Here's Form1.cs:

private void button1_Click(object sender, EventArgs e)
{
    MyData data = new MyData(boxEmail.Text, boxPass.Text, boxWorldId.Text);
    string objectNode = Serialize.ToJsonString(data);
    File.WriteAllText(Application.StartupPath + @"\LoginData.json", objectNode);
}
private void button2_Click(object sender, EventArgs e)
{   
    object myData;
    myData = Serialize.Deserialize<MyData>(new FileStream(Application.StartupPath + @"\LoginData.json", FileMode.Open));
    boxEmail.Text = data.Email;
    boxPass.Text = data.Password;
    boxWorldId.Text = data.WorldId;
}

Here's Serialize.cs:

public class Serialize
{
    public static StreamReader ToStreamReader(object o)
    {
        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
        ser.WriteObject(stream, o);
        stream.Position = 0;
        StreamReader sr = new StreamReader(stream);
        return sr;
    }
    public static string ToJsonString(object o)
    {
        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
        ser.WriteObject(stream, o);
        stream.Position = 0;
        StreamReader sr = new StreamReader(stream);
        return sr.ReadToEnd();
    }
    public static object Deserialize<T>(Stream stream)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        stream.Position = 0;
        T t = (T)ser.ReadObject(stream);
        return t;
    }
}

Also, this code was given to me by a friend, so I asked him. He couldn't understand it too. I asked another friend, who, in my opinion, knew decent C#, but he couldn't fix it too.

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll

Additional information: Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

Any opinions?

Aucun commentaire:

Enregistrer un commentaire