Table of Contents
C++ – nlohmann::json 구조체-json 변환하기
설치법
프로젝트에 파일하나 추가해주는 것으로 설치가 끝난다.
사용법
#include <string>
#include <iostream>
using namespace std;
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
struct Person {
string name;
int age;
}
두개의 함수를 생성해 줍니다.
void to_json(json& j, const Person& p) {
j = json{
{"name", p.name}
, {"age", p.age}
};
}
void from_json(const json& j, Person& p) {
j.at("name").get_to(p.name);
j.at("age").get_to(p.age);
}
\int main(void) {
// save to file
Person p = {"skyer9", 15};
json jf = p;
std::ofstream file("D:/gitrepo/test/test.json");
file << jf;
file.flush();
// read from file
std::ifstream ifs("D:/gitrepo/test/test.json");
json jf2 = json::parse(ifs);
Person p2 = jf2;
cout << p2.name << endl;
cout << p2.age << endl;
return 0;
}