rapidjson/example/sortkeys/sortkeys.cpp

57 lines
1.2 KiB
C++
Raw Normal View History

2018-12-04 22:40:40 +01:00
#include "rapidjson/document.h"
#include "rapidjson/filewritestream.h"
2018-12-04 22:40:40 +01:00
#include <rapidjson/prettywriter.h>
#include <algorithm>
#include <iostream>
using namespace rapidjson;
using namespace std;
2019-02-06 19:59:09 +08:00
static void printIt(const Value &doc) {
char writeBuffer[65536];
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
PrettyWriter<FileWriteStream> writer(os);
2018-12-04 22:40:40 +01:00
doc.Accept(writer);
cout << endl;
2018-12-04 22:40:40 +01:00
}
2019-02-06 19:59:09 +08:00
struct NameComparator {
2019-02-08 11:39:25 +08:00
bool operator()(const Value::Member &lhs, const Value::Member &rhs) const {
return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0);
2018-12-04 22:40:40 +01:00
}
};
2019-02-06 19:59:09 +08:00
int main() {
2019-02-06 20:35:20 +08:00
Document d(kObjectType);
2018-12-04 22:40:40 +01:00
Document::AllocatorType &allocator = d.GetAllocator();
d.AddMember("zeta", Value().SetBool(false), allocator);
d.AddMember("gama", Value().SetString("test string", allocator), allocator);
d.AddMember("delta", Value().SetInt(123), allocator);
2019-02-06 19:59:09 +08:00
d.AddMember("alpha", Value(kArrayType).Move(), allocator);
2018-12-04 22:40:40 +01:00
printIt(d);
2019-02-06 19:59:09 +08:00
/*
2018-12-04 22:40:40 +01:00
{
"zeta": false,
"gama": "test string",
"delta": 123,
"alpha": []
}
2019-02-06 19:59:09 +08:00
*/
2018-12-04 22:40:40 +01:00
std::sort(d.MemberBegin(), d.MemberEnd(), NameComparator());
2018-12-04 22:40:40 +01:00
printIt(d);
2019-02-06 19:59:09 +08:00
/*
2018-12-04 22:40:40 +01:00
{
"alpha": [],
"delta": 123,
"gama": "test string",
"zeta": false
}
2019-02-06 19:59:09 +08:00
*/
2018-12-04 22:40:40 +01:00
}