rapidjson:用于从文件中读取文档的工作代码

rapidjson: working code for reading document from file?

本文关键字:文档 工作 代码 读取 用于 文件 rapidjson      更新时间:2023-10-16

我需要一个可用的c++代码来使用rapidjson从文件中读取文档:https://code.google.com/p/rapidjson/

在wiki中,它还没有文档记录,示例仅从std::string中进行了非序列化,我对模板没有深入的了解。

我将文档序列化为一个文本文件,这是我编写的代码,但它没有编译:

#include "rapidjson/prettywriter.h" // for stringify JSON
#include "rapidjson/writer.h"   // for stringify JSON
#include "rapidjson/filestream.h"   // wrapper of C stream for prettywriter as output
[...]
std::ifstream myfile ("c:\statdata.txt");
rapidjson::Document document;
document.ParseStream<0>(myfile);

编译错误状态:错误:"Document"不是"rapidjson"的成员

我将Qt 4.8.1与mingw和rapidjson v0.1一起使用(我已经尝试过升级v0.11,但错误仍然存在)

#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <fstream>
using namespace rapidjson; 
using namespace std;
ifstream ifs("test.json");
IStreamWrapper isw(ifs);
Document d;
d.ParseStream(isw);

请阅读中的文档http://rapidjson.org/md_doc_stream.html。

@Raanan的答案中的FileStream显然不受欢迎。源代码中有一条注释,说要使用FileReadStream

#include <rapidjson/document.h>
#include <rapidjson/filereadstream.h>
using namespace rapidjson;
// ...
FILE* pFile = fopen(fileName.c_str(), "rb");
char buffer[65536];
FileReadStream is(pFile, buffer, sizeof(buffer));
Document document;
document.ParseStream<0, UTF8<>, FileReadStream>(is);

刚刚在遇到类似问题后发现了这个问题。解决方案是使用FILE*对象,而不是ifstream和rapidjson自己的FileStream对象(您已经包含了正确的头)

FILE * pFile = fopen ("test.json" , "r");
rapidjson::FileStream is(pFile);
rapidjson::Document document;
document.ParseStream<0>(is);

你当然需要添加文档.h-include(这回答了你的直接问题,但不会解决你的问题,因为你使用了错误的文件流):

#include "rapidjson/document.h"

然后,文档对象(我可能会添加得相当快)被文件内容填充。希望它能有所帮助!