如何在文件中添加Rapidjson ::文档

How to add rapidjson::Document in file

本文关键字:Rapidjson 文档 添加 文件      更新时间:2023-10-16

我需要解析文件,获取一些数据并使用Rapidjson将其写入另一个文件。

现在,我可以检索值并将其放入文档中。我唯一的问题是在文件中插入该文档:

FILE * pFile = fopen ("read.json" , "r");
FILE * wFile = fopen ("Test.json" , "w");
if (pFile != NULL)
{
    rapidjson::FileStream is(pFile);
    rapidjson::Document document;
    document.ParseStream<0>(is);
    string mMeshID = a.GetString();
    //how to add that document to wfile
    fclose (pFile);
}

有什么方法可以在文件中写下rappjson ::文档?

编辑:我发现的唯一方法是:

    // Convert JSON document to string
    GenericStringBuffer< UTF8<> > buffer;
    Writer<GenericStringBuffer< UTF8<> > > writer(buffer);
    doc.Accept(writer);
    const char* str = buffer.GetString();
    fprintf(wFile, "%s", str);
    fclose(wFile);

提出了有关FileWriteStream的更好文档。

使用FileWriteStream代替StringBuffer可以减少内存使用量。FileWriteStream使用固定大小的缓冲区(可以存储在堆栈中),而StringBuffer则需要将整个JSON存储在(HEAP)内存中。对于Big Json而言,这是一个很大的区别。

您最好使用

fwrite (buffer.GetString(), buffer.GetSize(), 1, wFile);

它更安全(如果缓冲区未终止终止),并且更快(没有strlen)。
除此之外,并且缺少错误检查您的代码,它很好,应该写入文件np。