rapidjson: working code for reading document from file?

℡╲_俬逩灬. 提交于 2019-12-22 04:42:43

问题


I need a working c++ code for reading document from file using rapidjson: https://code.google.com/p/rapidjson/

In the wiki it's yet undocumented, the examples unserialize only from std::string, I haven't a deep knowledge of templates.

I serialized my document into a text file and this is the code I wrote, but it doesn't compile:

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

the compilation error state: error: 'Document' is not a member of 'rapidjson'

I'm using Qt 4.8.1 with mingw and rapidjson v 0.1 (I already try with upgraded v 0.11 but the error remain)


回答1:


The FileStream in @Raanan's answer is apparently deprecated. There's a comment in the source code that says to use FileReadStream instead.

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



回答2:


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

Please read docs in http://rapidjson.org/md_doc_stream.html .




回答3:


Just found this question after having a rather similar problem. The solution would be to use a FILE* object, and not an ifstream together with rapidjson's own FileStream object (you already include the right header)

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

You of course need to add the document.h include (this answers your direct question, but will not solve the problem in your case, since you are using the wrong file stream):

#include "rapidjson/document.h"

The document object is then (rather fast i might add) filled with the file content. Hope it helps!



来源:https://stackoverflow.com/questions/18107079/rapidjson-working-code-for-reading-document-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!