실습에 사용한 json은 lib_json을 사용하였음.


우선 프로젝트 폴더에 json폴더(헤더파일이 담긴것)와 cpp들을 복사해줌.

그리고 cpp파일들을 프로젝트에 클래스추가시킨다.

-----------------------------------------------------------------------------------------------------------------


json을 이용한 파일 입력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "json/json.h"
...
 
// Value값을 만들고 거기에 데이터를 추가
Json::Value root;
root["userName"= "이름이다";
root["Attack"= 210;
root["Defence"= 300;
 
// 파일입력을 위해 StyledWriter를 이용
Json::StyledWriter sw;
std::string jsonString = sw.write(root);
 
FILE* pFile = NULL;
 
// 저장할수있는 위치를 알아서 찾아줌.
// 안드로이드 아이폰과 같이 권한없이는 접근하지 못하는 경우를 위해 사용하면 좋음
std::string fileName = FileUtils::getInstance()->getWritablePath();
fileName += "data.json";
 
fopen_s(&pFile, fileName.c_str(), "wt");
fwrite(jsonString.c_str(), jsonString.length(), 1, pFile);
fclose(pFile);
cs


기본적인 파일 입출력 함수들은 동일하고 나머지는 이런식으로 쓴다는걸 참고하면됨.

이렇게하면 가능한 저장위치에 data.json파일이 생성됨.

StyledWriter를 사용하면 알파벳순으로 정렬하여 입력됨.




json을 이용한 파일 출력 (Data 사용)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Json::Value root;
 
std::string fileName = FileUtils::getInstance()->getWritablePath();
fileName += "data.json";
 
Data data;
data = FileUtils::getInstance()->getDataFromFile(fileName);
 
char* pBuffer = (char*)data.getBytes();
std::string strJson = pBuffer;
 
// Reader를 이용하여 파일을 읽어와 root에 넣어줌
Json::Reader reader;
reader.parse(strJson.c_str(), root);
 
// root에서 값을찾아 형태에 맞게 바꿔줌
int atk = root["Attack"].asInt();
std::string userName = root["userName"].asString();
 
//출력
//MessageBox(userName.c_str(), "이름!!!");
 
//한글이 깨지는경우 아래와 같이 출력하면 깨짐없이 출력됨
MessageBoxA(NULL, userName.c_str(), "이름!!!", MB_OK);
cs




기타. value값을 배열이나 자식으로도 만들수있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Json::Value root;
Json::Value character;
 
// 아래와 같이 자식으로 넣을수도 있음
character["username"= "이름임";
character["Attack"= 210;
character["Defence"= 3000;
root["char"= character;
 
// 문자열대신 인트값을 넣어서 배열처럼 만들수도 있음
int index = 0;
root[index++= character;
root[index++= character;
root[index++= character;
cs


Posted by misty_
,