simplepullreader.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <rtthread.h>
  2. #include "rapidjson/reader.h"
  3. #include <iostream>
  4. #include <sstream>
  5. using namespace rapidjson;
  6. using namespace std;
  7. // If you can require C++11, you could use std::to_string here
  8. template <typename T> std::string stringify(T x) {
  9. std::stringstream ss;
  10. ss << x;
  11. return ss.str();
  12. }
  13. struct MyHandler {
  14. const char* type;
  15. std::string data;
  16. MyHandler() : type(), data() {}
  17. bool Null() { type = "Null"; data.clear(); return true; }
  18. bool Bool(bool b) { type = "Bool:"; data = b? "true": "false"; return true; }
  19. bool Int(int i) { type = "Int:"; data = stringify(i); return true; }
  20. bool Uint(unsigned u) { type = "Uint:"; data = stringify(u); return true; }
  21. bool Int64(int64_t i) { type = "Int64:"; data = stringify(i); return true; }
  22. bool Uint64(uint64_t u) { type = "Uint64:"; data = stringify(u); return true; }
  23. bool Double(double d) { type = "Double:"; data = stringify(d); return true; }
  24. bool RawNumber(const char* str, SizeType length, bool) { type = "Number:"; data = std::string(str, length); return true; }
  25. bool String(const char* str, SizeType length, bool) { type = "String:"; data = std::string(str, length); return true; }
  26. bool StartObject() { type = "StartObject"; data.clear(); return true; }
  27. bool Key(const char* str, SizeType length, bool) { type = "Key:"; data = std::string(str, length); return true; }
  28. bool EndObject(SizeType memberCount) { type = "EndObject:"; data = stringify(memberCount); return true; }
  29. bool StartArray() { type = "StartArray"; data.clear(); return true; }
  30. bool EndArray(SizeType elementCount) { type = "EndArray:"; data = stringify(elementCount); return true; }
  31. private:
  32. MyHandler(const MyHandler& noCopyConstruction);
  33. MyHandler& operator=(const MyHandler& noAssignment);
  34. };
  35. int simple_pull_reader() {
  36. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
  37. MyHandler handler;
  38. Reader reader;
  39. StringStream ss(json);
  40. reader.IterativeParseInit();
  41. while (!reader.IterativeParseComplete()) {
  42. reader.IterativeParseNext<kParseDefaultFlags>(ss, handler);
  43. cout << handler.type << handler.data << endl;
  44. }
  45. return 0;
  46. }
  47. MSH_CMD_EXPORT(simple_pull_reader, rapid json simple pull reader example);