首页 > 解决方案 > Save json with rapidjson directly on file

问题描述

I'm java programmer and I'm learning C++ for my personal project for a parser bitcoin core, my parser converts the information on file dat bitcoin to the json file.

Now my problem is when I create the big json with rapidjson with Writer on StringBuffer

This is a simple example my DAO

void DAOJson::serializationWithRapidJson(Person &person) {
    rapidjson::StringBuffer s;
    rapidjson::Writer<rapidjson::StringBuffer> writer(s);
    person.toRapidJson(writer);
    unique_ptr<string> json(new string(s.GetString()));
    cout << *json;
    ofstream stream(DIR_HOME + "dump_rapidJson_test.json");
    stream << *json;
    json.reset();
    stream.close();
}

My question is

Is possible with rapidjson create the json on the file and not on the string? because I must save my memory

the example of the code that I would like to

rapidjson::Writer<rapidjson::FileWriter> writer(s);

标签: c++c++11ofstreamrapidjson

解决方案


是的,你确实有OStreamWrapper

#include <rapidjson/ostreamwrapper.h>
#include <rapidjson/writer.h>
#include <fstream>

void f(auto person)
{
    std::ofstream stream(DIR_HOME + "dump_rapidJson_test.json");
    rapidjson::OStreamWrapper osw(stream);
    rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw);
    person.toRapidJson(writer);
}

如果我是你,我会定义一个运算符:

std::ofstream operator<<(std::ofstream& os, Person const& person)
{
    rapidjson::OStreamWrapper osw(os);
    rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw);
    person.toRapidJson(writer);
    return os;
}
// usage (e.g.):
std::ofstream out("tmp");
Person alice, bob;
out << "Alice: " << alice << "\nBob: " << bob;

您还有一个与 C 兼容的变体:rapidjson::FileWriteStream,但无论如何它都需要一个缓冲区。

#include <rapidjson/filewritestream.h>
#include <rapidjson/writer.h>
#include <cstdio>

void f(auto person)
{
    // output file (a la C)
    FILE* fp = std::fopen("output.json", "wb"); // non-Windows use "w"

    // writer to file (through a provided buffer)
    char writeBuffer[65536];
    rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    rapidjson::Writer<rapidjson::FileWriteStream> writer(os);

    // write
    person.toRapidJson(writer);
    std::fclose(fp);
}

推荐阅读