C
C#2y ago
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);
}
}
}
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);
}
}
}
4 Replies
Pascal
Pascal2y ago
your list entries are tuples, there isn't a representation for that in json. You can write a custom serializer or replace your list entries with a type that can be represented in json.
Primpy
PrimpyOP2y ago
I see, thanks :)
Pobiega
Pobiega2y ago
public record HighScore(string Name, int Score);
public record HighScore(string Name, int Score);
should do nicely 🙂
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server