Rapidjson: Is there a way to convert Object to std::string?

Created on 10 Mar 2016  路  5Comments  路  Source: Tencent/rapidjson

for example:

json string {"h":"d", "sub":{"q":1, "e":"22"}}

use rapidjson to parse it, we can get Value & sub = document["sub"], but sub is a Object, I want to convert it into a string({"q":1, "e":"22"}), i can not find any api (like std::string Object2str(Value & o) )to do that, so i have to travel every member of Object and convert them to string?

question

Most helpful comment

I am not sure what do you mean by converting an object to a string. If you mean converting a value to JSON, then it is the same as converting a document to JSON:

StringBuffer sb;
Writer<StringBuffer> writer(sb);
sub.Accept(writer);
std::string s = sb.GetString();

All 5 comments

I am not sure what do you mean by converting an object to a string. If you mean converting a value to JSON, then it is the same as converting a document to JSON:

StringBuffer sb;
Writer<StringBuffer> writer(sb);
sub.Accept(writer);
std::string s = sb.GetString();

thanks!

@miloyip I think this line:
Writer<StringBuffer> writer;
should be
Writer<StringBuffer> writer(sb);

@guoxiao Yes. I updated it. Thank you.

template<typename T>
string stringify(const T& o)
{
    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    o.Accept(writer);
    return sb.GetString();
}

Was this page helpful?
0 / 5 - 0 ratings