在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>>();
演示:https://godbolt.org/z/pGsxxn
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 将 AActor 引用传递到嵌套对象中
- 通过 id 访问 QML 插槽中的嵌套对象(从 c++ 调用)
- 我们可以在main函数中声明嵌套类对象吗
- 访问另一个类中的模板化嵌套类函数和对象
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- RapidJSON 文档创建嵌套对象
- Poco 迭代嵌套的 JSON 对象
- 具有嵌套对象优化的 C++ emplace_back
- 使用MPI/OpenMP的C 程序带有派生数据类型(嵌套类对象)容器
- 设计具有两个指向嵌套对象的指针的迭代器
- 如果嵌套对象具有相同的地址,编译器如何区分它们?
- C nlohmann如何迭代 /查找嵌套对象
- 在cpp中创建嵌套对象.下面的伪代码中的函数调用序列是什么
- tbb::flow::图的函数对象中嵌套对象的问题
- 如何访问boost::spirit::karma中嵌套对象的数据
- 谷物嵌套对象
- 在类中嵌套对象
- 如何以多态方式无限嵌套对象
- 尝试处理嵌套对象/结构和动态数组时出现内存泄漏或内存错误。可能的 Xcode/malloc 问题