NLOHMANN 的 JSON 库将数组转换为结构向量

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

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

假设我有一个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