[英]nlohmann's json library convert an array to a vector of structs
Say I have a json array that looks like this:假设我有一个如下所示的 json 数组:
[
{
"Name": "test",
"Val": "test_val"
},
{
"Name": "test2",
"Val": "test_val2"
}
]
I want to convert this into a vector of structs:我想将其转换为结构向量:
struct Test {
string Name;
string Val;
};
I know about the json.get<>()
method, but do not know how to apply that to this.我知道
json.get<>()
方法,但不知道如何将其应用于此。
For the automatic get<>
to work, you need to provide a mapping between JSON and your struct:要使自动
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);
}
Then it will work as expected.然后它将按预期工作。
auto parsed = json.get<std::vector<Test>>();
Demo: https://godbolt.org/z/9P1mjO演示: https : //godbolt.org/z/9P1mjO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.