simplepullreader.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include "rapidjson/reader.h"
  2. #include <iostream>
  3. using namespace rapidjson;
  4. using namespace std;
  5. struct MyHandler {
  6. const char* type;
  7. std::string data;
  8. bool Null() { type = "Null"; data.clear(); return true; }
  9. bool Bool(bool b) { type = "Bool:"; data = b? "true": "false"; return true; }
  10. bool Int(int i) { type = "Int:"; data = std::to_string(i); return true; }
  11. bool Uint(unsigned u) { type = "Uint:"; data = std::to_string(u); return true; }
  12. bool Int64(int64_t i) { type = "Int64:"; data = std::to_string(i); return true; }
  13. bool Uint64(uint64_t u) { type = "Uint64:"; data = std::to_string(u); return true; }
  14. bool Double(double d) { type = "Double:"; data = std::to_string(d); return true; }
  15. bool RawNumber(const char* str, SizeType length, bool) { type = "Number:"; data = std::string(str, length); return true; }
  16. bool String(const char* str, SizeType length, bool) { type = "String:"; data = std::string(str, length); return true; }
  17. bool StartObject() { type = "StartObject"; data.clear(); return true; }
  18. bool Key(const char* str, SizeType length, bool) { type = "Key:"; data = std::string(str, length); return true; }
  19. bool EndObject(SizeType memberCount) { type = "EndObject:"; data = std::to_string(memberCount); return true; }
  20. bool StartArray() { type = "StartArray"; data.clear(); return true; }
  21. bool EndArray(SizeType elementCount) { type = "EndArray:"; data = std::to_string(elementCount); return true; }
  22. };
  23. int main() {
  24. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
  25. MyHandler handler;
  26. Reader reader;
  27. StringStream ss(json);
  28. reader.IterativeParseInit();
  29. while (!reader.IterativeParseComplete()) {
  30. reader.IterativeParseNext<kParseDefaultFlags>(ss, handler);
  31. cout << handler.type << handler.data << endl;
  32. }
  33. return 0;
  34. }