diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index ff54199..9f53c9a 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -21,6 +21,7 @@ set(EXAMPLES simplereader simplepullreader simplewriter + sortkeys tutorial) include_directories("../include/") diff --git a/example/sortkeys/sortkeys.cpp b/example/sortkeys/sortkeys.cpp new file mode 100644 index 0000000..85e0807 --- /dev/null +++ b/example/sortkeys/sortkeys.cpp @@ -0,0 +1,66 @@ +#include "rapidjson/document.h" +#include "rapidjson/filewritestream.h" +#include + +#include +#include + +using namespace rapidjson; +using namespace std; + +void printIt(const Value &doc) +{ + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + PrettyWriter writer(os); + doc.Accept(writer); + + cout << endl; +} + +struct NameComparator +{ + bool + operator()(const GenericMember, MemoryPoolAllocator<>> &lhs, + const GenericMember, MemoryPoolAllocator<>> &rhs) const + { + return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0); + } +}; + +int main() +{ + Document d = Document(kObjectType); + 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); + + Value a(kArrayType); + d.AddMember("alpha", a, allocator); + + printIt(d); + + /** +{ + "zeta": false, + "gama": "test string", + "delta": 123, + "alpha": [] +} +**/ + + std::sort(d.MemberBegin(), d.MemberEnd(), NameComparator()); + + printIt(d); + /** +{ + "alpha": [], + "delta": 123, + "gama": "test string", + "zeta": false +} +**/ + return 0; +}