Salocin
Salocin

Reputation: 403

Empty String Serialization with Datacontracts

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";
    }
}

Upvotes: 3

Views: 983

Answers (1)

Mixim
Mixim

Reputation: 972

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());
                }
            }
        }

Upvotes: 6

Related Questions