C#C
C#3y ago
4 replies
Primpy

❔ JsonSerializer serializes list as if its entries were empty

The data inside my List<(string, int)> looks fine but whenever I try to serialize it and save it to a file, I get empty lines. What am I doing wrong?

public class Leaderboard
    {
        public List<(string, int)> HighScores { get; set; }
        public const int MAX_HIGHSCORES_COUNT = 5;
        public const string HIGHSCORES_FILE_PATH = "./Data/highscores.json";

        public Leaderboard()
        {
            HighScores = new() { ("Test", 123) };
        }

        public void Load()
        {
            if (File.Exists(HIGHSCORES_FILE_PATH))
            {
                string jsonString = File.ReadAllText(HIGHSCORES_FILE_PATH);
                var leaderboard = JsonSerializer.Deserialize<Leaderboard>(jsonString)!;
                HighScores = new(leaderboard.HighScores);
            }
            else
            {
                Save();
            }
        }

        public void Save()
        {
            var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(this, options);
            File.WriteAllText(HIGHSCORES_FILE_PATH, jsonString);
        }

        public void Add(string name, int score)
        {
            if (HighScores.Count < MAX_HIGHSCORES_COUNT || score >= HighScores[HighScores.Count - 1].Item2)
            {
                HighScores.Add(new(name, score));
                HighScores.Sort();
                if (HighScores.Count > MAX_HIGHSCORES_COUNT)
                    HighScores.RemoveAt(HighScores.Count - 1);
            }
        }
    }
image.png
image.png
Was this page helpful?