我试图使用rapidjson库解析一个基本的std ::字符串向量到json。
尽管网上有这个问题的答案有多个,但这些答案对我来说都不起作用。我能找到的最好的是this,但我确实收到了一个错误(清理了一下):
错误C2664'noexcept':无法将参数1从'std :: basic_string,std :: allocator>'转换为'rapidjson :: GenericObject,rapidjson :: MemoryPoolAllocator >>'
我的代码主要基于上面的链接:
rapidjson::Document d;
std::vector<std::string> files;
// The Vector gets filled with filenames,
// I debugged this and it works without errors.
for (const auto & entry : fs::directory_iterator(UPLOAD_DIR))
files.push_back(entry.path().string());
// This part is based on the link provided
d.SetArray();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
for (int i = 0; i < files.size(); i++) {
d.PushBack(files.at(i), allocator);
}
rapidjson::StringBuffer strbuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
d.Accept(writer);
jsonString = strbuf.GetString();
如果有人能解释我在这里缺少的东西会很好,因为我不完全理解出现的错误。我想它必须对提供的字符串类型做一些事情,但错误是在Rapidjson文件中生成的。
如果您可以提供其他工作示例,我也将不胜感激。
提前致谢!
编辑使用JSON数组我的意思是只是一个包含矢量值的基本json字符串。
似乎字符串类型std :: string和rapidjson :: UTF8不兼容。我设置了一个小的测试程序,如果你创建一个rapidjson :: Value对象并首先调用它的SetString方法,它似乎有效。
#include <iostream>
#include <vector>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
int main() {
rapidjson::Document document;
document.SetArray();
std::vector<std::string> files = {"abc", "def"};
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
for (const auto file : files) {
rapidjson::Value value;
value.SetString(file.c_str(), file.length(), allocator);
document.PushBack(value, allocator);
// Or as one liner:
// document.PushBack(rapidjson::Value().SetString(file.c_str(), file.length(), allocator), allocator);
}
rapidjson::StringBuffer strbuf;
rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
document.Accept(writer);
std::cout << strbuf.GetString();
return 0;
}
x2struct是rapidjson的包装器,你可以用它来转换C ++对象和json。
#include <iostream>
#include "x2struct/x2struct.hpp"
using namespace std;
int main(int argc, char*argv[]) {
vector<string> v;
v.push_back("hello");
v.push_back("world");
string json = x2struct::X::tojson(v); // vector to json
cout<<json<<endl;
return 0;
}
输出是:
["hello","world"]