9

我需要一个工作 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'的成员

我正在使用带有 mingw 和 rapidjson v 0.1 的 Qt 4.8.1(我已经尝试使用升级的 v 0.11,但错误仍然存​​在)

4

3 回答 3

16
#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中的文档。

于 2016-09-19T04:16:19.770 回答
14

@RaananFileStream的答案显然已被弃用。源代码中有一条注释说要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);
于 2013-10-27T17:47:47.683 回答
6

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

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

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

#include "rapidjson/document.h"

然后(我可能会添加相当快的)文档对象填充文件内容。希望能帮助到你!

于 2013-08-28T13:58:17.813 回答