messagereader.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Reading a message JSON with Reader (SAX-style API).
  2. // The JSON should be an object with key-string pairs.
  3. #include "rapidjson/reader.h"
  4. #include "rapidjson/error/en.h"
  5. #include <iostream>
  6. #include <string>
  7. #include <map>
  8. using namespace std;
  9. using namespace rapidjson;
  10. typedef map<string, string> MessageMap;
  11. #if defined(__GNUC__)
  12. RAPIDJSON_DIAG_PUSH
  13. RAPIDJSON_DIAG_OFF(effc++)
  14. #endif
  15. struct MessageHandler : public BaseReaderHandler<> {
  16. MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {}
  17. bool StartObject() {
  18. switch (state_) {
  19. case kExpectObjectStart:
  20. state_ = kExpectNameOrObjectEnd;
  21. return true;
  22. default:
  23. return false;
  24. }
  25. }
  26. bool String(const char* str, SizeType length, bool) {
  27. switch (state_) {
  28. case kExpectNameOrObjectEnd:
  29. name_ = string(str, length);
  30. state_ = kExpectValue;
  31. return true;
  32. case kExpectValue:
  33. messages_.insert(MessageMap::value_type(name_, string(str, length)));
  34. state_ = kExpectNameOrObjectEnd;
  35. return true;
  36. default:
  37. return false;
  38. }
  39. }
  40. bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; }
  41. bool Default() { return false; } // All other events are invalid.
  42. MessageMap messages_;
  43. enum State {
  44. kExpectObjectStart,
  45. kExpectNameOrObjectEnd,
  46. kExpectValue,
  47. }state_;
  48. std::string name_;
  49. };
  50. #if defined(__GNUC__)
  51. RAPIDJSON_DIAG_POP
  52. #endif
  53. void ParseMessages(const char* json, MessageMap& messages) {
  54. Reader reader;
  55. MessageHandler handler;
  56. StringStream ss(json);
  57. if (reader.Parse(ss, handler))
  58. messages.swap(handler.messages_); // Only change it if success.
  59. else {
  60. ParseErrorCode e = reader.GetParseErrorCode();
  61. size_t o = reader.GetErrorOffset();
  62. cout << "Error: " << GetParseError_En(e) << endl;;
  63. cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl;
  64. }
  65. }
  66. int main() {
  67. MessageMap messages;
  68. const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
  69. cout << json1 << endl;
  70. ParseMessages(json1, messages);
  71. for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr)
  72. cout << itr->first << ": " << itr->second << endl;
  73. cout << endl << "Parse a JSON with invalid schema." << endl;
  74. const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
  75. cout << json2 << endl;
  76. ParseMessages(json2, messages);
  77. return 0;
  78. }