C++ std::vector to JSON Array with rapidjson

C++ std::vector to JSON Array with rapidjson

本文关键字:Array with JSON rapidjson to std vector C++      更新时间:2023-10-16

我正在尝试使用rapidjson库将字符串的基本std::vector解析为json。

尽管网上有多个答案,但没有一个对我有用。我能找到的最好的就是这个,但我确实得到了一个错误(清理了一点):

错误 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;
}