250211 TIL

박소희·2025년 2월 11일

Unity_7기

목록 보기
24/94

JSON으로 데이터 저장하기

  • 객체를 JSON 형식 문자열로 변환 -> JSON 데이터를 파일로 저장 -> JSON 파일을 읽어서 객체로 변환
  1. 파일 입출력 이용
  2. 데이터 직렬화
  • System.Text.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;
}

0개의 댓글