使用 nlohmann json 将整数列表解压缩为 std::vector<int>

Use nlohmann json to unpack list of integers to a std::vector<int>

我正在使用 https://github.com/nlohmann/json

太棒了。

但是..有什么办法解压:

{
    "my_list" : [1,2,3]
}

变成 std:vector<int> ?

我找不到任何提及,std::vector<int> v = j["my_list"];j["my_list"].get<std::vector<int>>()

一样失败

交联到 https://github.com/nlohmann/json/issues/1460

所以它确实有效。我没有隔离测试用例,我的 JSON 字符串格式不正确。

所以,

json J(json_string);
J["my_list"].get<std::vector<int>>()

有效。

在我的例子中,我确保我的 C++ 变量名与 JSON 键匹配,所以我可以简单地使用宏:

#define EXTRACT(x) x = J[#x].get< decltype(x) >()

int foo;
std::vector<float> bar;

EXTRACT(foo);
EXTRACT(bar);