nlohmann的json库将数组转换为结构向量 [英] nlohmann's json library convert an array to a vector of structs
本文介绍了nlohmann的json库将数组转换为结构向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个看起来像这样的json数组:
Say I have a json array that looks like this:
[
{
"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;
};
我了解json.get<>()
方法,但是不知道如何将其应用于此方法.
I know about the json.get<>()
method, but do not know how to apply that to this.
推荐答案
要使自动get<>
起作用,您需要在JSON和结构之间提供一个映射:
For the automatic get<>
to work, you need to provide a mapping between JSON and your struct:
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
这篇关于nlohmann的json库将数组转换为结构向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文