Home > Mobile >  JSON Serializer returns empty file
JSON Serializer returns empty file

Time:01-27

I have managed to create minimum reproducible example here:

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

File Cache.json is created, but it only contains {}, which means that these properties were ignored and not saved. Perhaps something is wrong with the WriteToJsonFile method, but in some cases it seems to work. And it was approved answer in one of stackoverflow questions.

CodePudding user response:

JSON serializers in C# tend to make use of properties, not fields. These are just fields:

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

Make them properties:

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