c++ - 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);
解决方案
是的,你确实有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);
}
推荐阅读
- jquery - jquery sortable 在排序前删除下一行
- angular - Angular 7 AmCharts PDF 字体
- python - 尝试使用 ' 'join(x.split()) 删除一些重复的空格但失败
- c# - 如何在 .ASP.NET Core MVC 中使用多个登录页面以及未经授权的用户重定向不同的登录页面
- clojure - core.async 通道 - 跟踪时发生的情况(示例)
- sql - 带有 json 数组的 find_by 使用 IN 执行查询而不是搜索整个数组
- html - 自定义复选框:使用 css 在取消选中添加十字图标?
- python - “我正在尝试根据选择的下拉值获取单行的值。输出出错。”
- javascript - 异步/等待调用
- spring - @SqlResultSetMapping 使用导致架构验证问题