4

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

2 に答える 2

13

文字列を取得したら、それをファイルに書き込むのは簡単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もあります。

于 2014-04-04T07:08:34.527 に答える