Programming

RapidJson 사용 정리

DragonTory 2021. 5. 13. 14:58
반응형

RapidJson 사용 정리 

 

가끔 c++에서 json을 사용 할 때

사용법을 잊어 버려서

간단 사용 예제를 만들어 저장 해 놓습니다. 

 

 

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
#include <string>
#include <sstream>
#include <iostream>
 
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h" 
 
using namespace rapidjson; 
 
bool ParseJson(Document &doc, const std::string& jsonData)
{
    if (doc.Parse(jsonData.c_str()).HasParseError())
    {
        return false;
    }
 
    return doc.IsObject();
 
    //rapidjson::ParseResult result = doc.Parse(jsonData.c_str());
    //if (result.IsError())
    //printf( "RapidJson parse error: %s (%lu)\n", rapidjson::GetParseError_En(result.Code()), result.Offset());
    //return !result.IsError();
}
 
std::string JsonDocToString(Document &doc, bool isPretty = false)
{
    StringBuffer buffer;
    if( isPretty )
    {
        PrettyWriter<StringBuffer> writer(buffer);
        doc.Accept(writer);
    }
    else
    {
        Writer<StringBuffer> writer(buffer);
        doc.Accept(writer);    
    }    
    return buffer.GetString();
}
 
void TestJson_Parse() 
{
    // 1. Parse a JSON string into DOM.
    const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
    Document doc;
    ParseJson(doc, json);
 
    // 2. Modify it by DOM.
    Value& s = doc["stars"];
    s.SetInt(s.GetInt() + 1);
 
    std::string jsonString = JsonDocToString(doc, true);
    printf( jsonString.c_str() );    
}
 
void TestJson_AddMember() 
{
    // 1. Parse a JSON string into DOM.
    //Document doc;
    //doc.SetObject();
    Document doc(kObjectType);
     
    Document::AllocatorType& allocator = doc.GetAllocator();    
    doc.AddMember("project""rapidjson", allocator);
    doc.AddMember("stars"10, allocator);
 
    std::string jsonString = JsonDocToString(doc, true);
    printf( jsonString.c_str() );    
}
 
cs

 

출력 :

TestJson_Parse()

{
    "project": "rapidjson",
    "stars": 11
}

 

TestJson_AddMember()

{
    "project": "rapidjson",
    "stars": 10
}

 

RapidJson 문서 & github

https://rapidjson.org/

 

RapidJSON: Main Page

A fast JSON parser/generator for C++ with both SAX/DOM style API Tencent is pleased to support the open source community by making RapidJSON available. Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. Build status Introduction RapidJSON

rapidjson.org

https://github.com/Tencent/rapidjson/blob/master/example/tutorial/tutorial.cpp

 

 

Tencent/rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API - Tencent/rapidjson

github.com

 

 

 

반응형