sortkeys.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <rtthread.h>
  2. #include "rapidjson/document.h"
  3. #include "rapidjson/filewritestream.h"
  4. #include <rapidjson/prettywriter.h>
  5. #include <algorithm>
  6. #include <iostream>
  7. using namespace rapidjson;
  8. using namespace std;
  9. static void printIt(const Value &doc) {
  10. char writeBuffer[65536];
  11. FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
  12. PrettyWriter<FileWriteStream> writer(os);
  13. doc.Accept(writer);
  14. cout << endl;
  15. }
  16. struct NameComparator {
  17. bool operator()(const Value::Member &lhs, const Value::Member &rhs) const {
  18. return (strcmp(lhs.name.GetString(), rhs.name.GetString()) < 0);
  19. }
  20. };
  21. int sortkeys() {
  22. Document d(kObjectType);
  23. Document::AllocatorType &allocator = d.GetAllocator();
  24. d.AddMember("zeta", Value().SetBool(false), allocator);
  25. d.AddMember("gama", Value().SetString("test string", allocator), allocator);
  26. d.AddMember("delta", Value().SetInt(123), allocator);
  27. d.AddMember("alpha", Value(kArrayType).Move(), allocator);
  28. printIt(d);
  29. /*
  30. {
  31. "zeta": false,
  32. "gama": "test string",
  33. "delta": 123,
  34. "alpha": []
  35. }
  36. */
  37. // C++11 supports std::move() of Value so it always have no problem for std::sort().
  38. // Some C++03 implementations of std::sort() requires copy constructor which causes compilation error.
  39. // Needs a sorting function only depends on std::swap() instead.
  40. #if __cplusplus >= 201103L || (!defined(__GLIBCXX__) && (!defined(_MSC_VER) || _MSC_VER >= 1900))
  41. std::sort(d.MemberBegin(), d.MemberEnd(), NameComparator());
  42. printIt(d);
  43. /*
  44. {
  45. "alpha": [],
  46. "delta": 123,
  47. "gama": "test string",
  48. "zeta": false
  49. }
  50. */
  51. #endif
  52. }
  53. MSH_CMD_EXPORT(sortkeys, rapid json sort keys example);