nlohmann 的 json 库将数组转换为结构向量

nlohmann's json library convert an array to a vector of structs

假设我有一个 json 数组,如下所示:

[
  {
    "Name": "test",
    "Val": "test_val"
  },
  {
    "Name": "test2",
    "Val": "test_val2"
  }
]

我想将其转换为结构向量:

struct Test {
  string Name;
  string Val;
};

我知道 json.get<>() 方法,但不知道如何应用它。

要使自动 get<> 起作用,您需要提供 JSON 和您的结构之间的映射:

void from_json(const nlohmann::json& j, Test& p) {
    j.at("Name").get_to(p.Name);
    j.at("Val").get_to(p.Val);
}

然后它将按预期工作。

auto parsed = json.get<std::vector<Test>>();

演示:https://godbolt.org/z/9P1mjO