最简单的做法是尽可能使用 C 数组,std::array
而不是 C 数组。std::array
是普通数组的 C++ 类似物,它添加了来自std::vector
likesize()
和迭代器的所有好东西。与 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