使用Datacontracts的空字符串序列化

时间:2016-09-19 16:44:46

标签: c# json serialization datacontractserializer netdatacontractserializer

我有一个我能想到的最通用的序列化示例:一个包含两个变量和一个实例的类,我想序列化。 但是我有一个问题,下面的代码总是让我一个空字符串。我没想到为什么会这样......

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

1 个答案:

答案 0 :(得分:5)

因为您的信息流已结束。将您的代码更改为:

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