Jsonxx - iterate through Json

Jsonxx - iterate through Json

本文关键字:Json through iterate Jsonxx      更新时间:2023-10-16

我正在使用 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;
}