如何使用RapidJSON将压缩后的JSON结果存储到C++ string而非输出到stdout
How to Store RapidJSON Output to a C++ String (Instead of stdout)
Both of your questions—capturing compressed JSON output and redirecting parser output to a string—share the same core solution in RapidJSON: swap out the FileWriteStream (which writes to stdout/files) with RapidJSON's StringBuffer to capture output in memory, then convert that buffer to a C++ std::string. Here's how to adjust your example code:
Modified Example Code
#include "rapidjson/reader.h" #include "rapidjson/writer.h" #include "rapidjson/filereadstream.h" #include "rapidjson/stringbuffer.h" // Add this header for in-memory buffer #include "rapidjson/error/en.h" #include <string> // For std::string support using namespace rapidjson; int main() { // --- Original input setup (reading from stdin) --- char readBuffer[65536]; FILE* fp = stdin; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); // --- Replace FileWriteStream with StringBuffer --- StringBuffer outputBuffer; // Stores output in memory instead of stdout Writer<StringBuffer> writer(outputBuffer); // Attach writer to the in-memory buffer // --- Parse and process (same logic, but output goes to buffer) --- Reader reader; if (!reader.Parse(is, writer)) { fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); return 1; } // --- Convert StringBuffer to C++ std::string --- std::string compressedJson(outputBuffer.GetString(), outputBuffer.GetSize()); // Now you can use 'compressedJson' for storage, processing, etc. // Optional: Verify the result by printing it printf("Compressed JSON stored in string:\n%s\n", compressedJson.c_str()); return 0; }
Key Changes Explained
- Add
StringBufferheader: Include<rapidjson/stringbuffer.h>to access RapidJSON's in-memory output buffer. - Replace
FileWriteStream: Instead of writing directly to stdout, we useStringBufferto hold the processed JSON data in RAM. - Convert to
std::string: UseoutputBuffer.GetString()(returns a null-terminatedconst char*) andoutputBuffer.GetSize()to safely initialize a C++ string.
For DOM-Based Workflows
If you're using a parsed Document instead of the direct Reader/Writer pipeline, the same approach works to serialize the DOM to a string:
// Assume you have a populated rapidjson::Document doc StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); std::string jsonString(buffer.GetString(), buffer.GetSize());
This method handles both compressed (whitespace-free) JSON output and any other parser/writer output you want to capture in a string instead of printing to stdout.
内容的提问来源于stack exchange,提问作者HarshGiri
相关产品推荐
相关产品推荐

