Add project files.
This commit is contained in:
52
Program.cs
Normal file
52
Program.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
|
||||
using Serialization_Demo.Model;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Serialization_Demo
|
||||
{
|
||||
class Program
|
||||
{
|
||||
private static List<Player> players = new List<Player>();
|
||||
private static string filePath = "players.json";
|
||||
static async Task Main(string[] args) // <-- HIER async Task Main
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
players = await DeserializePlayersAsync(filePath); // <-- await
|
||||
Console.WriteLine("Players loaded from file:");
|
||||
foreach (var player in players)
|
||||
{
|
||||
Console.WriteLine($"Name: {player.Name}, Score: {player.Score}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
players = new List<Player>
|
||||
{
|
||||
new Player { Name = "Player 1", Score = 100 },
|
||||
new Player { Name = "Player 2", Score = 200 },
|
||||
new Player { Name = "Player 3", Score = 300 }
|
||||
};
|
||||
|
||||
await SerializePlayersAsync(players, filePath); // <-- await
|
||||
Console.WriteLine($"Players ({players.Count}) written to file");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static async Task SerializePlayersAsync(List<Player> players, string filePath)
|
||||
{
|
||||
string json = JsonSerializer.Serialize(players);
|
||||
await File.WriteAllTextAsync(filePath, json); // <-- async versie
|
||||
}
|
||||
|
||||
private static async Task<List<Player>> DeserializePlayersAsync(string filePath)
|
||||
{
|
||||
string json = await File.ReadAllTextAsync(filePath); // <-- async versie
|
||||
List<Player> players = JsonSerializer.Deserialize<List<Player>>(json);
|
||||
return players ?? new List<Player>(); // kleine extra check
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user