繁体   English   中英

C ++ std :: vector到带有RapidJSON的JSON数组

[英]C++ std::vector to JSON Array with rapidjson

我正在尝试使用RapidJSON库将基本的std :: vector字符串解析为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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM