使用Rapidjson在文件中写入
Write in file using Rapidjson
如何使用Rapidjson文档将一些数据写入文件:
这是我需要写的:
"Big Node ": [
{ "Big Key": "Key Value 1", "Child Key": "Key Value 1", "Values": [ 1, 3, 4, 1, 2, 3 ] },
{ "Big Key": "Key Value 2", "Child Key": "Key Value 2", "Values": [ 17, 18, 5, 4, 17] }
]
一旦获得字符串,将其写入文件就像std::ofstream (path) << string
一样容易。
这是将json写入文件的示例:
char cbuf[1024]; rapidjson::MemoryPoolAllocator<> allocator (cbuf, sizeof cbuf);
rapidjson::Document meta (&allocator, 256);
meta.SetObject();
meta.AddMember ("foo", 123, allocator);
typedef rapidjson::GenericStringBuffer<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> StringBuffer;
StringBuffer buf (&allocator);
rapidjson::Writer<StringBuffer> writer (buf, &allocator);
meta.Accept (writer);
std::string json (buf.GetString(), buf.GetSize());
std::ofstream of ("/tmp/example.json");
of << json;
if (!of.good()) throw std::runtime_error ("Can't write the JSON string to the file!");
如果要避免双重延误,则可以直接写入ofstream
:
struct Stream {
std::ofstream of {"/tmp/example.json"};
typedef char Ch;
void Put (Ch ch) {of.put (ch);}
void Flush() {}
} stream;
rapidjson::Writer<Stream> writer (stream, &allocator);
meta.Accept (writer);
还有filewritestream。
来自官方文档:filewritestream
创建JSON文档:
...通过解析:
const char json[] = " { "hello" : "world", "t" : true , "f" : false, "n": null, "i":123, "pi": 3.1416, "a":[1, 2, 3, 4] } ";
Document d;
d.Parse(json);
...或通过编程设置值创建值:
Document d;
d.SetObject();
d.AddMember ("Foo", 123, d.GetAllocator());
并写入文件:
#include "rapidjson/filewritestream.h"
#include <rapidjson/writer.h>
//...
FILE* fp = fopen("output.json", "wb"); // non-Windows use "w"
char writeBuffer[65536];
FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
d.Accept(writer);
fclose(fp);
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何使用 rapidjson 读取 json 文件并输出到 std::string?
- 使用 rapidjson 直接在文件中保存 json
- 使用RapidJson凝结JSON文件后,如何将输出存储在C 字符串中
- 如何使用矢量数据使用 rapidjson 库创建 json 文件<string>?
- 使用Rapidjson在文件中写入
- 如何在文件中添加Rapidjson ::文档
- 如何使用 Rapidjson 解析文件获得"node"?
- Rapidjson未读取文件
- 使用rapidjson从json文件中获取数组数据
- rapidjson:用于从文件中读取文档的工作代码
- 如何使用rapidjson C++在JSON文件中检索键值数据
- 我想用RapidJSON编辑一个文件,但当我这样做时,文件不会被保存
- 如何使用rapidjson合并两个json文件