在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量

in nlohmann json how can I convert an array of nested objects into a vector of nested structs?

本文关键字:嵌套 对象 数组 向量 结构 转换 json nlohmann      更新时间:2023-10-16

我问了这个问题,答案非常适用于常规(非嵌套(对象:

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

带有结构:

struct Test {
string Name;
string Val;
};

然而,当我尝试使用嵌套结构时,比如:

struct Inner {
string Name;
string Value;
};
struct Outer {
string Display;
int    ID;
Inner  Nested
};
//with json
"
[
{
"Display": "abcd",
"ID": 100,
"Nested": {
"Name": "Test Name",
"Value": "Test Value"
}
}
]
"

它给了我一个错误:

In function 'void from_json(const json&, Outer&)':
parser/run.cc:16:41: error: no matching function for call to 'nlohmann::basic_json<>::get_to(std::vector<Inner>&) const'
j.at("Inner").get_to(p.Inner);

错误消息听起来像是为Outer而不是Inner编写了一个辅助函数。只要为每个用户定义的类型编写一个辅助函数,库就可以处理嵌套结构:

void from_json(const nlohmann::json& j, Inner& i) {
j.at("Name").get_to(i.Name);
j.at("Value").get_to(i.Value);
}
void from_json(const nlohmann::json& j, Outer& o) {
j.at("Display").get_to(o.Display);
j.at("ID").get_to(o.ID);
j.at("Nested").get_to(o.Nested);
}

然后它就像你想要的那样工作:

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

演示:https://godbolt.org/z/pGsxxn