【问题标题】:Write in file using Rapidjson使用 Rapidjson 写入文件
【发布时间】:2014-02-04 13:12:01
【问题描述】:

如何使用 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]   }
             ]

【问题讨论】:

  • 还有一个神奇的问题...您尝试过什么,究竟有什么问题?有带有User Guide 和示例的文档。还有几个关于这个主题的问题。
  • 我查看了用户指南,但他们没有提供任何写入文件的方法。现在写,我在文件中添加了一些数据,唯一的问题是如何处理如此复杂的数据。事实上你可以看到另一个数组里面有一个数组......

标签: c++ rapidjson


【解决方案1】:

获得字符串后,将其写入文件就像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

【讨论】:

    【解决方案2】:

    来自官方文档: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);
    

    ...或通过编程设置值CreateModifyValues:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2012-06-07
      • 2021-05-29
      • 2011-05-20
      相关资源
      最近更新 更多