How to serialize RapidJSON document to a string?

Lochana Thenuwara picture Lochana Thenuwara · Oct 23, 2015 · Viewed 31.1k times · Source

How to serialize RapidJSON document to a string?
In all the examples the serializing text is redirected to the standard output through the FileStream, but I need to redirect it to a string variable.

Answer

A.Franzen picture A.Franzen · Oct 26, 2015

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.