Native JSON Benchmark 비교 자료를 참고하면 어떤 JSON 라이브러리를 선택할지 조금이나마 도움이 될 수 있습니다.
다만 관련 자료가 Rapid JSON 라이브러리 작성자이기 때문에 객관적인 결과일까 하는 의문이 들긴 합니다. 그럼에도 불구하고, 저는 RapidJSON의 헤더 폴더를 개발 프로젝트의 include 디렉토리에 복사만 해서 바로 사용할 수 있어 RapdJSON을 주로 사용하고 있습니다.
RapidJSON 사용법
1. GitHub에서 라이브러리를 다운로드 받습니다.
$ git clone https://github.com/Tencent/rapidjson.git
2. 헤더파일(include) 폴더를 프로젝트에 복사합니다.
3. API를 사용하여 코드를 작성합니다.
// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. Parse a JSON string into DOM.
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
// 2. Modify it by DOM.
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
return 0;
}
참 쉽죠잉~
더 상세한 내용은 참고 사이트의 문서를 살펴보시기 바랍니다.
쉬워 보이기는 하지만 약간 복잡해지면 이것저것 신경써서 코딩해야 합니다. 오브젝트를 포함한 배열을 추가할 때는 조금 삽질을 했습니다. 아래 URL을 참고하세요.
■ 원하는 결과가 아래와 같을 때
{
"year": 2022,
"league": "kbo",
"teams": [
{
"teamname": "ssg",
"teamcity": "incheon",
"roster": [
{
"playername": "kim",
"position": "catcher"
},
{
"playername": "chu",
"position": "pitcher"
}
]
}
]
}
■ 구현은...
rapidjson::Document jsonDoc;
jsonDoc.SetObject();
rapidjson::Value myArray(rapidjson::kArrayType);
rapidjson::Document::AllocatorType& allocator = jsonDoc.GetAllocator();
std::vector<Roster*>::iterator iter = roster.begin();
std::vector<Roster*>::iterator eiter = roster.end();
for (; iter != eiter; ++iter) {
rapidjson::Value objValue;
objValue.SetObject();
objValue.AddMember("playername", (*iter)->PlayerName().c_str(), allocator);
objValue.AddMember("position", (*iter)->Position().c_str(), allocator);
myArray.PushBack(objValue, allocator);
}
jsonDoc.AddMember("array", myArray, allocator);
rapidjson::StringBuffer strbuf;
rapidjson::Writer<rapidjson::StringBuffer>
writer(strbuf);
jsonDoc.Accept(writer);
const char *jsonString = strbuf.GetString();
// to examine the encoding...
참고 사이트
- Miloyip's RapidJSON GitHub
- Rapid JSON Documentation
- How to Parse an Array of Objects in C++ Using RapidJson?
- How to Read and Parse Json File with RapidJson?
'Programming > Libraries' 카테고리의 다른 글
C++ Library: spdlog (0) | 2022.10.07 |
---|