언어 정리/c#

c# 데이터 저장 <Newtonsoft.Json 활용>

rimugiri 2024. 1. 7. 22:29
728x90

0. 저장할 클래스 설정

     class Player
      {
          // public으로 선언해 줘야 데이터 저장 및 불러오기가 가능하다
          public int Hp { get; set; }
          public int Attack { get; set; }
          public int Defense { get; set; }

          public Player(int hp, int attack, int defense)
          {
              Hp = hp;
              Attack = attack;
              Defense = defense;
          }
      }

1. 데이터 저장 -> Json파일로 저장

        public void SaveData(Player player)
        {
            string FilePath = "./PlayerData.json"; // 파일경로설정
            try
            {
                string json = JsonConvert.SerializeObject(player, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(FilePath, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error saving data: {ex.Message}");
            }
        }

데이터 저장을 원하는 파일 경로를 설정해 주면 그 공간에 json데이터를 설정해 준다.

2. 데이터 불러오기 -> Json파일 데이터 불러오기

        public Player LoadData()
        {
            string FilePath = "../../PlayerData.json"; // 데이터 저장한 파일 경로 설정
            try
            {
                if (File.Exists(FilePath))
                {
                    string json = File.ReadAllText(FilePath);
                    return JsonConvert.DeserializeObject<Player>(json);
                }
                else
                {
                    // 파일 미 존재 시 기본 데이터 설정
                    return new Player(200, 20, 5);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Load data: {ex.Message}");
                // JsonConver 오류 발생 시 기본 데이터 설정 
                return new Player(200, 20, 5);
            }
        }

3. 간단한 예제

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 데이터 저장 예제
            Player player = new Player(300,20,10);
            SaveData(Player);

            // 데이터 불러오기 예제
            // Player player = LoadData();
            // Console.WriteLine($"Hp : {player.Hp}\nAttack : {player.Attack}\nDefense : {player.Defense}");
        }
        static void SaveData(Player player)
        {
            string FilePath = "../../../PlayerData.json"; // 파일경로설정
            try
            {
                string json = JsonConvert.SerializeObject(player, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(FilePath, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error saving data: {ex.Message}");
            }
        }
        static Player LoadData()
        {
            string FilePath = "../../../PlayerData.json"; // 데이터 저장한 파일 경로 설정
            try
            {
                if (File.Exists(FilePath))
                {
                    string json = File.ReadAllText(FilePath);
                    return JsonConvert.DeserializeObject<Player>(json);
                }
                else
                {
                    // 파일 미 존재 시 기본 데이터 설정
                    return new Player(200, 20, 5);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Load data: {ex.Message}");
                // JsonConver 오류 발생 시 기본 데이터 설정 
                return new Player(200, 20, 5);
            }
        }
    }
    class Player
    {
        // public으로 선언해 줘야 데이터 저장 및 불러오기가 가능하다
        public int Hp { get; set; }
        public int Attack { get; set; }
        public int Defense { get; set; }

        public Player(int hp, int attack, int defense)
        {
            Hp = hp;
            Attack = attack;
            Defense = defense;
        }
    }
}
728x90