Skip to content

Commit c9060b4

Browse files
committed
added example for sorting keys
1 parent 30d92a6 commit c9060b4

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

example/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ set(EXAMPLES
2121
simplereader
2222
simplepullreader
2323
simplewriter
24+
sortkeys
2425
tutorial)
2526

2627
include_directories("../include/")

example/sortkeys/sortkeys.cpp

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#define RAPIDJSON_HAS_STDSTRING 1
2+
#include "rapidjson/document.h"
3+
#include <rapidjson/prettywriter.h>
4+
#include <rapidjson/stringbuffer.h>
5+
6+
#include <algorithm>
7+
#include <iostream>
8+
9+
using namespace rapidjson;
10+
using namespace std;
11+
12+
void printIt(Document &doc)
13+
{
14+
string output;
15+
StringBuffer buffer;
16+
PrettyWriter<StringBuffer> writer(buffer);
17+
doc.Accept(writer);
18+
19+
output = buffer.GetString();
20+
cout << output << endl;
21+
}
22+
23+
struct ValueNameComparator
24+
{
25+
bool
26+
operator()(const GenericMember<UTF8<>, MemoryPoolAllocator<>> &lhs,
27+
const GenericMember<UTF8<>, MemoryPoolAllocator<>> &rhs) const
28+
{
29+
string lhss = string(lhs.name.GetString());
30+
string rhss = string(rhs.name.GetString());
31+
return lhss < rhss;
32+
}
33+
};
34+
35+
int main()
36+
{
37+
Document d = Document(kObjectType);
38+
Document::AllocatorType &allocator = d.GetAllocator();
39+
40+
d.AddMember("zeta", Value().SetBool(false), allocator);
41+
d.AddMember("gama", Value().SetString("test string", allocator), allocator);
42+
d.AddMember("delta", Value().SetInt(123), allocator);
43+
44+
Value a(kArrayType);
45+
d.AddMember("alpha", a, allocator);
46+
47+
printIt(d);
48+
49+
/**
50+
{
51+
"zeta": false,
52+
"gama": "test string",
53+
"delta": 123,
54+
"alpha": []
55+
}
56+
**/
57+
58+
std::sort(d.MemberBegin(), d.MemberEnd(), ValueNameComparator());
59+
60+
printIt(d);
61+
/**
62+
{
63+
"alpha": [],
64+
"delta": 123,
65+
"gama": "test string",
66+
"zeta": false
67+
}
68+
**/
69+
return 0;
70+
}

0 commit comments

Comments
 (0)