使用nlohmann json将整数列表解包到std::vector<int>中。

13

我正在使用nlohman::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进行交叉链接。


1
看起来你需要手动迭代 xx.items() 将元素 push_back 到向量中。(https://nlohmann.github.io/json/classnlohmann_1_1basic__json_afe3e137ace692efa08590d8df40f58dd.html#afe3e137ace692efa08590d8df40f58dd) - bruno
1
使用from_json转换到一个中间的std::array吗?阅读它们的源代码(https://nlohmann.github.io/json/json_8hpp_source.html)并不容易。 - bruno
1个回答

25

实际上它是可以工作的。我没有分离出一个测试用例,而且我的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);

我仍然有一个运行时错误,我很好奇你是如何解决它的... - jokoon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接