]>
git.proxmox.com Git - ceph.git/blob - ceph/src/rapidjson/example/messagereader/messagereader.cpp
1 // Reading a message JSON with Reader (SAX-style API).
2 // The JSON should be an object with key-string pairs.
4 #include "rapidjson/reader.h"
5 #include "rapidjson/error/en.h"
11 using namespace rapidjson
;
13 typedef map
<string
, string
> MessageMap
;
17 RAPIDJSON_DIAG_OFF(effc
++)
22 RAPIDJSON_DIAG_OFF(switch-enum)
26 : public BaseReaderHandler
<UTF8
<>, MessageHandler
> {
27 MessageHandler() : messages_(), state_(kExpectObjectStart
), name_() {}
31 case kExpectObjectStart
:
32 state_
= kExpectNameOrObjectEnd
;
39 bool String(const char* str
, SizeType length
, bool) {
41 case kExpectNameOrObjectEnd
:
42 name_
= string(str
, length
);
43 state_
= kExpectValue
;
46 messages_
.insert(MessageMap::value_type(name_
, string(str
, length
)));
47 state_
= kExpectNameOrObjectEnd
;
54 bool EndObject(SizeType
) { return state_
== kExpectNameOrObjectEnd
; }
56 bool Default() { return false; } // All other events are invalid.
61 kExpectNameOrObjectEnd
,
75 static void ParseMessages(const char* json
, MessageMap
& messages
) {
77 MessageHandler handler
;
78 StringStream
ss(json
);
79 if (reader
.Parse(ss
, handler
))
80 messages
.swap(handler
.messages_
); // Only change it if success.
82 ParseErrorCode e
= reader
.GetParseErrorCode();
83 size_t o
= reader
.GetErrorOffset();
84 cout
<< "Error: " << GetParseError_En(e
) << endl
;;
85 cout
<< " at offset " << o
<< " near '" << string(json
).substr(o
, 10) << "...'" << endl
;
92 const char* json1
= "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
93 cout
<< json1
<< endl
;
94 ParseMessages(json1
, messages
);
96 for (MessageMap::const_iterator itr
= messages
.begin(); itr
!= messages
.end(); ++itr
)
97 cout
<< itr
->first
<< ": " << itr
->second
<< endl
;
99 cout
<< endl
<< "Parse a JSON with invalid schema." << endl
;
100 const char* json2
= "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
101 cout
<< json2
<< endl
;
102 ParseMessages(json2
, messages
);