JSON转换为nlohmann JSON-lib中的结构数组

JSON to an array of structs in nlohmann json lib

本文关键字:结构 数组 JSON-lib 转换 nlohmann JSON      更新时间:2023-10-16

我最近问了一个关于将对象数组转换为结构向量的问题。我想做同样的事情,但向量我想要一个数组。例如

[
{
"Name": "Test",
"Val": "TestVal"
},
{
"Name": "Test2",
"Val": "TestVal2"
}
]

想要这些结构的数组:

struct Test {
string Name;
string Val;
};

这怎么可能呢?我是c++的新手,所以如果我做错了什么,请这么说。

最简单的方法是尽可能使用std::array而不是C数组。std::array是一个类似于普通数组的C++,它添加了std::vector中所有漂亮的东西,比如size()和迭代器。与C数组不同,您也可以从函数返回它们。

nlohmann还自动支持:

auto parsed = json.get<std::array<Test, 2>>();

不确定库是否支持普通的ol’C数组。但你可以用一点模板魔法来编写一个辅助函数:

template <typename T, size_t N>
void from_json(const nlohmann::json& j, T (&t)[N]) {
if (j.size() != N) {
throw std::runtime_error("JSON array size is different than expected");
}
size_t index = 0;
for (auto& item : j) {
from_json(item, t[index++]);
}
}

用法:

Test my_array[N];
from_json(json, my_array);

演示:https://godbolt.org/z/-jDTdj