JSON으로 데이터 저장하기
public class PlayerData
public class GameData
직렬화
public static void SaveGameData(GameData data, string filePath)
{
string json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true }); // 객체를 JSON 문자열로 변환
File.WriteAllText(filePath, json); // JSON 문자열을 파일로 저장
}
역직렬화
public static GameData LoadGameData(string filePath)
{
if (!File.Exists(filePath))
{
Console.WriteLine("저장된 게임 데이터가 없습니다.");
return null;
}
string json = File.ReadAllText(filePath); // JSON 파일을 문자열로 읽음.
GameData data = JsonSerializer.Deserialize<GameData>(json); // JSON을 객체로 변환
Console.WriteLine("게임 데이터를 불러왔습니다!");
return data;
}