stringify with rapidjson

Robert Cervera picture Robert Cervera · Nov 2, 2012 · Viewed 11k times · Source

I'm using socket.io-clientpp, https://github.com/ebshimizu/socket.io-clientpp, which uses rapidjson.

When a event is received, my function is called :

void data_published(socketio::socketio_events&, const Value& v) {

Value is a rapidjson value. My problem is that the only way I see to stringify it is with Document class. But to put the Value in a Document, all functions take a non-const reference, for example :

GenericValue& AddMember(const Ch* name, GenericValue& value, Allocator& allocator) {

I'm used to jsonpp, I'm missing something silly I guess. The question is simple : how to stringify a const rapidjson Value ?

Answer

Milo Yip picture Milo Yip · Nov 14, 2012

I am the author of rapidjson. Thank you for your question. I recorded this to issue in http://code.google.com/p/rapidjson/issues/detail?id=45

It is due to that GenericValue::Accept() is non-const.

As GenericValue::Accept() just generates events for handler, it does not need to modify the value and its decedents. So it should change from:

template <typename Handler>
GenericValue& Accept(Handler& handler)

to

template <typename Handler>
const GenericValue& Accept(Handler& handler) const

You may patch this to your rapidjson/document.h or download the latest version (trunk or 0.1x branch).

After this change, you can stringfy a const Value as in tutorial:

const Value& v = ...;
FileStream f(stdout);
PrettyWriter<FileStream> writer(f);
v.Accept(writer);

Or to a string buffer:

const Value& v = ...;
StringBuffer buffer;
PrettyWriter<StringBuffer> writer(buffer);
v.Accept(writer);
const char* json = buffer.GetString();