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

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

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

尽管这个问题在网上有多个答案,none 其中对我有用。我能找到的最好的是 this,但我确实得到了一个错误(稍微清理了一下):

Error C2664 'noexcept': cannot convert argument 1 from 'std::basic_string,std::allocator>' to 'rapidjson::GenericObject,rapidjson::MemoryPoolAllocator>>'

我的代码主要基于上面的link:

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