0

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

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

并想要这些结构的数组:

struct Test {
  string Name;
  string Val;
};

这怎么可能?我是 C++ 新手,所以如果我做错了什么,请说出来。

4

1 回答 1

3

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

于 2020-02-21T01:32:26.693 回答