7

我正在使用 socket.io-clientpp,https://github.com/ebshimizu/socket.io-clientpp,它使用 rapidjson。

当收到一个事件时,我的函数被调用:

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

值是一个 rapidjson 值。我的问题是我看到将其字符串化的唯一方法是使用 Document 类。但是要将值放入文档中,所有函数都采用非常量引用,例如:

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

我习惯了 jsonpp,我想我错过了一些愚蠢的东西。问题很简单:如何对 const rapidjson 值进行字符串化?

4

1 回答 1

17

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();
于 2012-11-14T07:30:12.160 回答