Kipaboy
Kipaboy

Reputation: 11

XML Deserializer - object is empty

I want to converts objects to xml and reverse. I can serialize my objects without any problems to an xml document using this method:

public static void SaveObjectToXML(T _obj, string fileName)
{
   XmlSerializer ser = new XmlSerializer(typeof(T));
   FileStream str = new FileStream(fileName, FileMode.Create);
   ser.Serialize(str, _obj);
   str.Close();
}

But with the Deserializer I've got some problems... While the process I get no Errors or problems (same for calling methods of it) but when I try do acess any members the problem begins. All members are null (same for methods acessing any members). Heres the code:

public static T SaveXMLToObject(string fileName)
{
   XmlSerializer ser = new XmlSerializer(typeof(T));
   StreamReader sr = new StreamReader(fileName);
   T dataSet = (T)ser.Deserialize(sr);
   return dataSet;
}

Any Ideas?


edit:

OK I just added the using Statement, thanks for that :) The complete classes are a bit to much, but they look like this:

public class User
{
   private string _name;
   public string Name
   {
     get { return _name; }
     set { }
   }
}

public class AllUser
{
   private User[] _users;
   public User[] Users
   {
      get { return _users; }
      set { }
   }
}

Upvotes: 0

Views: 801

Answers (2)

Ilia G
Ilia G

Reputation: 10211

Assuming sample code is complete I am not surprised at all. You have empty setters (which is what serialization will use). Don't just satisfy serialization error by adding empty setter. It is required for populating your data.

Changes that to

set { _users = value; }

and it should work

Upvotes: 2

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

I think you just need to mark the classes you are deserializing to as [Serializable]. For example:

[Serializable]
public class User
{
    ...
}

Upvotes: -1

Related Questions