[英]in nlohmann json how can I convert an array of nested objects into a vector of nested structs?
I asked this question, and the answer worked perfectly for regular (un-nested) objects:我问了这个问题,答案非常适用于常规(非嵌套)对象:
[
{
"Name": "test",
"Val": "test_val"
},
{
"Name": "test2",
"Val": "test_val2"
}
]
with the struct:使用结构:
struct Test {
string Name;
string Val;
};
However when I tried to use nested structs, like so:但是,当我尝试使用嵌套结构时,如下所示:
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"
}
}
]
"
It gave me this error:它给了我这个错误:
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);
The error message sounds like you wrote a helper function for Outer
, but not Inner
.错误消息听起来像是您为Outer
而不是Inner
编写了一个辅助函数。 As long as you write a helper function for each user-defined type, the library can handled nested structs:只要为每个用户定义的类型编写一个辅助函数,库就可以处理嵌套结构:
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);
}
Then it works like you want it to:然后它就像你想要的那样工作:
auto parsed = json.get<std::vector<Outer>>();
Demo: https://godbolt.org/z/pGsxxn演示: https : //godbolt.org/z/pGsxxn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.