在 nlohmann json 如何将嵌套对象数组转换为嵌套结构向量?
in nlohmann json how can I convert an array of nested objects into a vector of nested structs?
我问了 个问题,答案非常适合常规(非嵌套)对象:
[
{
"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>>();
我问了
[
{
"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>>();