用rapidjson进行字符串化

Rob*_*era 6 c++ json rapidjson

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

收到事件后,我的函数被调用:

void data_published(socketio::socketio_events&, const Value& v) {
Run Code Online (Sandbox Code Playgroud)

值是rapidjson值.我的问题是我看到字符串化的唯一方法是使用Document类.但是要将Value放在Document中,所有函数都采用非const引用,例如:

GenericValue& AddMember(const Ch* name, GenericValue& value, Allocator& allocator) {
Run Code Online (Sandbox Code Playgroud)

我习惯了jsonpp,我猜想我有些傻了.问题很简单:如何将const rapidjson值字符串化?

Mil*_*Yip 14

我是rapidjson的作者.谢谢你的问题.我在http://code.google.com/p/rapidjson/issues/detail?id=45中记录了此问题

这是因为GenericValue :: Accept()是非const的.

由于GenericValue :: Accept()只为处理程序生成事件,因此不需要修改值及其后代.所以它应该改变:

template <typename Handler>
GenericValue& Accept(Handler& handler)
Run Code Online (Sandbox Code Playgroud)

template <typename Handler>
const GenericValue& Accept(Handler& handler) const
Run Code Online (Sandbox Code Playgroud)

您可以将其修补到rapidjson/document.h或下载最新版本(trunk或0.1x分支).

在此更改之后,您可以像教程中一样对一个const值进行stringfy:

const Value& v = ...;
FileStream f(stdout);
PrettyWriter<FileStream> writer(f);
v.Accept(writer);
Run Code Online (Sandbox Code Playgroud)

或者到字符串缓冲区:

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