我正在使用Jsonxx library
我需要遍历一些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覆盖任何内容。它们的实现仅适用于标准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*>&


你也需要改变
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++ - Jsonxx-遍历Json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35090884/

10-13 09:31