Search code examples
c++stringdocumentrapidjson

How to serialize RapidJSON document to a string?


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.


Solution

  • 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.