简体   繁体   English

使用 Rapidjson 写入文件

[英]Write in file using Rapidjson

How can i write some data into file using rapidjson document :如何使用 Rapidjson 文档将一些数据写入文件:

Here is what i need to write :这是我需要写的:

"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]   }
             ]

Once you get the string, writing it to a file is as easy as std::ofstream (path) << string .获得字符串后,将其写入文件就像std::ofstream (path) << string一样简单。

Here's an example writing JSON to a file:这是将 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!");

If you want to avoid the double-buffering then you can write directly to ofstream :如果你想避免双缓冲,那么你可以直接写入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);

There's also FileWriteStream .还有FileWriteStream

From the official doc: FileWriteStream来自官方文档: FileWriteStream

Create json document:创建json文档:

...by parsing: ...通过解析:

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

... or by setting values programmatically CreateModifyValues : ...或通过以编程方式设置值CreateModifyValues

Document d; 
d.SetObject();
d.AddMember ("Foo", 123, d.GetAllocator());

And write to file:并写入文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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