How to serialize RapidJSON document to a string?
Like this:
const char *GetJsonText()
{
rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
return strdup( buffer.GetString() );
}
Then of couse you have to call free() on the return, or do:
return string( buffer.GetString() );
instead.
In the first page of the project, the code already shows how to serialize a document into a string (stringify a document):
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
buffer.GetString()
here returns a string of const char*
type. It also has a buffer.GetSize()
for returning the size of output string. So, if you would convert it to a std::string
, the best way is:
std::string s(buffer.GetString(), buffer.GetSize());
The tutorial.cpp also show the same thing, in addition to other common usage of RapidJSON.
Example code:
Document document;
const char *json = " { \"x\" : \"0.01\", \"y\" :\"0.02\" , \"z\" : \"0.03\"} ";
document.Parse<0>(json);
//convert document to string
StringBuffer strbuf;
strbuf.Clear();
Writer<StringBuffer> writer(strbuf);
document.Accept(writer);
std::string ownShipRadarString = strbuf.GetString();
std::cout << "**********************************************" << ownShipRadarString << std::endl;