【问题标题】:Empty String Serialization with Datacontracts使用 Datacontracts 进行空字符串序列化
【发布时间】:2017-01-27 10:27:41
【问题描述】:

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

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

【问题讨论】:

    标签: c# json serialization datacontractserializer netdatacontractserializer


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!我在这上面花了 1.5 小时……当你从互联网上复制代码部分而不了解其背后的所有概念时,这就是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多