JSON 到 nlohmann json 库中的结构数组

JSON to an array of structs in nlohmann json lib

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

[
  {
    "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 数组不同,您还可以 return 从函数中获取它们。

nlohmann 也自动支持:

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

不确定库是否支持普通的 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