简体   繁体   中英

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);

Yes, you do have 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);
}

I'd define an operator if I were you:

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;

You alsohave a C-compatible variant: rapidjson::FileWriteStream , but it needs a buffer anyway.

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM