3

I have the most generic example of Serialization I can think of: a class with two variables and one instance of it, I would like to serialize. However I have the problem that the code below always gets me an empty string. I run out of ideas why this could be..

    public static async void SaveState()
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(new Deck().GetType());

        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, new Deck());
            using (var sr = new StreamReader(stream))
            {
                Debug.WriteLine(sr sr.ReadToEnd());
            }
        }      
    }




[DataContract]
class Deck
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public int Points { get; set; } = 1500;


    public Deck()
    {
        this.Name = "Deck Name";
    }
}
Salocin
  • 393
  • 6
  • 17

1 Answers1

6

Because your stream is at the end. Change your code to:

public static void Main (string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(new Deck().GetType());

            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, new Deck());
                stream.Position = 0;//the key.
                using (var sr = new StreamReader(stream))
                {
                    Console.WriteLine(sr.ReadToEnd());
                }
            }
        }
Mixim
  • 972
  • 1
  • 11
  • 37
  • 1
    Thank you so much! I've spent 1.5h on that... That's the problem when you copy code parts from the internet without understanding all concepts behind it. – Salocin Sep 19 '16 at 16:57