【问题标题】:JSON Serializer returns empty fileJSON 序列化程序返回空文件
【发布时间】:2023-01-27 02:55:30
【问题描述】:

我设法在这里创建了最小的可重现示例:

internal class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();

            Cache sc = new Cache();
            sc.Enabled = true;
            sc.Path = @"C:\File.txt";

            p.WriteToJsonFile("Cache.json", sc);
        }

        private void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
        {
            TextWriter writer = null;
            try
            {
                var contentsToWriteToFile = JsonSerializer.Serialize(objectToWrite);
                writer = new StreamWriter(filePath, append);
                writer.Write(contentsToWriteToFile);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

        internal class Cache
        {
            public string Path = string.Empty;
            public bool Enabled;
        }
    }

文件Cache.json 已创建,但它只包含{},这意味着这些属性被忽略且未保存。也许 WriteToJsonFile 方法有问题,但在某些情况下它似乎有效。它在其中一个 stackoverflow 问题中得到了批准的答案。

【问题讨论】:

    标签: c# json .net


    【解决方案1】:

    C# 中的 JSON 序列化器倾向于使用特性, 不是字段.这些只是字段:

    internal class Cache
    {
        public string Path = string.Empty;
        public bool Enabled;
    }
    

    使它们具有属性:

    internal class Cache
    {
        public string Path { get; set; } = string.Empty;
        public bool Enabled { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2022-12-03
      • 1970-01-01
      相关资源
      最近更新 更多