Search code examples
c#jsonserializationdatacontractserializernetdatacontractserializer

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

Solution

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