使用PrettyWriter将RapidJSON文档写入文件

时间:2018-11-20 08:22:36

标签: rapidjson

我一直无法找到这个问题的直接答案。经过一段时间的搜索,我编写了以下代码,但是我确定存在一种更简单的方法来执行相同的任务。

int persistJSONChanges(rapidjson::Document& fa_cloneDoc, string jsonFilePath)
{
        FILE* lp_file = fopen(jsonFilePath.c_str(), "w");
        rapidjson::StringBuffer buffer;
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
        fa_cloneDoc.Accept(writer);

        string temp=buffer.GetString();
        unique_ptr<char[]>l_writeBuffer(new char[temp.size()]);
        rapidjson::FileWriteStream l_writeStream(lp_file, l_writeBuffer.get(), temp.size());
        rapidjson::PrettyWriter<rapidjson::FileWriteStream> l_writer(l_writeStream);
        bool l_returnStatus=fa_cloneDoc.Accept(l_writer);
        if(l_returnStatus==false)
        {
                cout<<endl<<"file update failed"<<endl;
                return -1;
           }
        fclose(lp_file);
        return 0;
}

3 个答案:

答案 0 :(得分:1)

我认为您滥用了FileWriteStream。它只需要一个任意大小的缓冲区。

您只需要:

FILE* fp = fopen(...);
char buffer[1024];
FileWriteStream fs(fp, buffer, sizeof(buffer));
PrettyWriter<FileWriteStream> writer(fs);
document.Accept(writer);
fclose(fp);

答案 1 :(得分:0)

我尝试了以下对我有用的方法:

int persistJSONChanges(rapidjson::Document& fa_cloneDoc, string jsonFilePath)
{

                rapidjson::StringBuffer buffer;
                rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
                bool l_returnStatus=fa_cloneDoc.Accept(writer);
                if(l_returnStatus==false)
                {
                        fprintf(stdout,"\n[%s::%d] JSON File update failed\n",__FILE__,__LINE__);

                        return -1;
                }

                string temp=buffer.GetString();
                ofstream out(jsonFilePath.c_str(),std::ofstream::trunc);
                out<<temp;
                return 0;
}

答案 2 :(得分:0)

我不使用

    rapidjson::Document

这对我有用:

    namespace rpj = rapidjson; 

    FILE* fp_r = fopen("json.json", "w" );

    char buf[BUF_SIZE];

    rpj::FileWriteStream os(fp_r, buf, sizeof (buf));

    rpj::PrettyWriter<rpj::FileWriteStream> writer(os);

    writer.StartObject();
    writer.String("hello");
    writer.String("world");
    writer.String("arr");
    writer.StartArray();
    writer.Int(33);
    writer.Int(34);
    writer.Int(36);
    writer.EndArray();
    writer.EndObject();

    fclose(fp_r);