본문 바로가기
c#/수업내용

2020.04.22 json파일 역직렬화, 직렬화 Achievement

by Luna_O 2020. 4. 22.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace study_014_1
{
    class App
    {
        Dictionary<int, GameAchievementData> dicGameAchievementDatas;
        Dictionary<int, GameAchievementInfo> dicGameAchievementInfo;
        GameAchievementData[] arrGameAchievementDatas;
        public App()
        {
            //매핑클래스(바인딩 클래스) 생성 
            //GameAchievementData.cs
            //id, name, goal, reward_type, reward_amount, desc
 
            //File 읽고 문자열 변수에 할당
            string path = "./gameachievement_data.json";
            string json = File.ReadAllText(path);
            //Console.WriteLine(json);
 
            //위에서 할당된 값(json형식의 문자열)를 가지고 객체를 생성(JsonConvert.DeserializeObject..)
            arrGameAchievementDatas = JsonConvert.DeserializeObject<GameAchievementData[]>(json);
 
            //생성된 객체(배열객체)를 Dictionary에 옮겨 담기
 
            this.dicGameAchievementDatas = new Dictionary<int, GameAchievementData>();
 
            foreach (GameAchievementData data in arrGameAchievementDatas)
            {
                this.dicGameAchievementDatas.Add(data.id, data);
            }
 
            this.dicGameAchievementInfo = new Dictionary<int, GameAchievementInfo>();
 
            //Info파일 불러 오기 
            string infoPath = "./gameachievementInfo_data.json";
 
            //만약에 info저장 파일이 있다면
            if (File.Exists(infoPath))
            {
                //기존 유저
                Console.WriteLine("!!!기존유저!!!");
                //파일 불러오기
                string infoJson = File.ReadAllText(infoPath);
 
                //불러온 문자열을 배열객체로 변환 역직렬화
                GameAchievementInfo[] arrinfos = JsonConvert.DeserializeObject<GameAchievementInfo[]>(infoJson);
 
                //만든 배열객체를 Dictionary에 담는다
                foreach (GameAchievementInfo info in arrinfos)
                {
                    this.dicGameAchievementInfo.Add(info.id, info);
                }
            }
            //그렇지않고 파일이 없다면
            else
            {
                //신규 유저
                Console.WriteLine("!!!신규 유저!!!");
                //info 객체를 생성하고 Dictionary에 추가한다
                foreach (KeyValuePair<int, GameAchievementData> pair in dicGameAchievementDatas) //사전에 담는다
                {
                    GameAchievementData data = pair.Value;  //data값을 할당하기 위해 변수 할당
                    GameAchievementInfo info = new GameAchievementInfo(data.id, 0);  //info객체를 생성하고 변수에 할당
 
                    this.dicGameAchievementInfo.Add(info.id, info); //Dictionary에 info 객체 추가
                }
                //파일 저장
                this.SaveAchievements();
            }
            //데이터 준비 끝
 
            //info 클래스 생성
            //data 클래스는 정보가 바뀌면 안됨
            //바뀌는 정보는 info 클래스에 멤버변수로 할당
 
            //info 객체를 생성하고 Dictionary에 추가한다
            //this.dicGameAchievementInfo = new Dictionary<int, GameAchievementInfo>();  //추가 할 사전 생성
 
            /*foreach (KeyValuePair<int, GameAchievementData> pair in dicGameAchievementDatas) //사전에 담는다
            {
                GameAchievementData data = pair.Value;  //data값을 할당하기 위해 변수 할당
                GameAchievementInfo info = new GameAchievementInfo(data.id, 0);  //info객체를 생성하고 변수에 할당
 
            }*/
 
            this.PrintAchievement(1000); //업적 보기
            this.DoAchievement(1000);    //업적 하기
            this.PrintAchievement(1000);
            this.SaveAchievements();     //업적 파일로 저장하기
 
        }
 
        public void PrintAchievement(int id)  //업적 보기 메서드
        {
            GameAchievementData data = this.dicGameAchievementDatas[id];  //업적에 대한 data 호출
            GameAchievementInfo info = this.dicGameAchievementInfo[id];   //업적에 대한 info 호충
 
            string format = string.Format(data.desc, info.count);
 
            Console.WriteLine("{0}: {1} ({2}/{3})"data.name, format, info.count, data.goal);
        }
        public void DoAchievement(int id)  //업적 하기
        {
            GameAchievementData data = this.dicGameAchievementDatas[id];
 
            Console.WriteLine("{0} 업적을 1번 완료했습니다."data.name);
 
            //id에 해당하는 AchievementInfo객체를 찾아서 
            GameAchievementInfo info = this.dicGameAchievementInfo[id];
            //멤버변수 count에 1을 더해준다
            info.count++;
        }
        public void SaveAchievements()  //업적 파일로 저장하기
        {
            //info 사전에 들어있는 객체들의 수만큼 배열을 만든다
            int length = this.dicGameAchievementInfo.Count;
            GameAchievementInfo[] arr = new GameAchievementInfo[length];
 
            //새로만든 배열에  dicGameAchievementInfo에 들어있는 객체들을 담는다
            for (int i = 0; i < this.dicGameAchievementInfo.Count; i++)
            {
                GameAchievementData data = this.arrGameAchievementDatas[i];
                arr[i] = this.dicGameAchievementInfo[data.id];
            }
            //배열객체 -> json 형식의 문자열로 변환 
            string json = JsonConvert.SerializeObject(arr);
            //Console.WriteLine(json);
 
            //파일 저장 
            string path = "./gameachievementInfo_data.json";
            File.WriteAllText(path, json);
        }
 
    }
}