simplepullreader.cpp 2.2 KB

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