Jsonxx - iterate through Json
Jsonxx - iterate through Json
我正在使用 Jsonxx 库我需要遍历一些 json 值,例如:
{
"unknowName1" : { "foo" : bar }
"unknowName2" : { "foo" : bar }
}
很明显,我需要某种迭代器,但我做不到,jsonxx 不是很受欢迎或文档丰富。不幸的是,我无法使用其他 json 库。我试过这个:
Object o;
o.parse(json);
std::map<std::string, Value*> * jsonMap = o.kv_map;
typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for (it_type iterator = jsonMap->begin(); iterator != jsonMap->end(); iterator++)
{
doing stuff here
}
但是 jsonxx 既不提供迭代器的转换,也不覆盖 "!=" 运算符。
但是 jsonxx 既不提供迭代器的转换,也不覆盖 "!=" 运算符。
这是一种误解。jsonxx
不需要覆盖任何东西。它们的实现仅与标准 c++ 容器实现配合良好。
从他们的(诚然记录不佳)界面来看,您实际上需要一个const_iterator
typedef std::map<std::string, std::map<std::string, Value*>>::const_iterator it_type;
// ^^^^^^^^
因为 kv_map()
函数返回一个const std::map<std::string, Value*>&
签名如标题所示:
const std::map<std::string, Value*>& kv_map() const;
你也需要改变
std::map<std::string, Value*> * jsonMap = o.kv_map;
自
const std::map<std::string, Value*>& jsonMap = o.kv_map();
// ^ ^^ it's a function, so call it
// | there's no pointer returned but a const reference
以获得正确的语法。
最后,循环应如下所示:
for (it_type iterator = jsonMap.begin(); iterator != jsonMap.end(); ++iterator) {
// doing stuff here
}
如果您使用的是 C++11 及更高版本,则可以使用自动初始化非常轻松地进行迭代,从而产生如下结果:
for(auto kv : o.kv_map)
{
jsonxx::Object obj = kv.second->get<jsonxx::Object>();
// do stuff here
std::cout << obj.json() << std::endl;
}
相关文章:
- 在c++中使用nlohmann从类到json的转换
- C++json插入数组
- nlohmann-json将一个数组插入到另一个数组中
- 如何使用curlpp通过POST方法上传文件和json数据
- JSON转换为nlohmann JSON-lib中的结构数组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 nlohmann 的 json 库中获取数组长度?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray
- 如何在特定位置追加 json 文件
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 使用 jsoncpp 解析 json 数组字符串
- 将 FlatBuffer 对象序列化为 JSON,而不使用其架构文件
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 使用 cmake 生成 compile_commands.json
- 如何使用 c++ 和提升库生成 json
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- 使用 Qt 解析 JSON 数组
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- Jsonxx - iterate through Json