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

C++ 在nlohmann json中,如何将嵌套对象数组转换为嵌套结构向量?,c++,json,nlohmann-json,C++,Json,Nlohmann Json,我问了一个问题,答案对常规(非嵌套)对象非常有效: 对于结构: struct Test { string Name; string Val; }; 但是,当我尝试使用嵌套结构时,例如: struct Inner { string Name; string Value; }; struct Outer { string Display; int ID; Inner Nested }; //with json " [ { "Display":

我问了一个问题,答案对常规(非嵌套)对象非常有效:

对于结构:

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);
函数“void from_json(const json&,Outer&)”中的

parser/run.cc:16:41:错误:调用“nlohmann::basic_json::get_to(std::vector&)const”时没有匹配的函数
j、 在(“内部”)。到达(内部);

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

void from_json(const nlohmann::json&j,Inner&i){
j、 在(“姓名”)。到达(即姓名);
j、 在(“价值”)。获得(i.价值);
}
void from_json(const nlohmann::json&j,Outer&o){
j、 在(“显示器”)。到达(o.Display);
j、 在(“ID”)。到达(o.ID);
j、 在(“嵌套”)。获取到(o.Nested);
}
然后,它会像您希望的那样工作:

auto-parsed=json.get();
演示:

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);