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
'언어 정리 > c#' 카테고리의 다른 글
c# int[,]와 int[][]의 차이점 (0) | 2024.01.11 |
---|---|
c# NewtonSoft.json 활용 데이터 저장 <interface 데이터 추가> (0) | 2024.01.07 |
[c#] Console 다룰 때 알아두면 좋은 기능 (1) | 2024.01.06 |
LeetCode - 300(동적 프로그래밍) (1) | 2024.01.02 |
LeetCode - 733번 문제 bfs를 통한 해결 (0) | 2024.01.02 |