gpt4 book ai didi

c++ - Jsonxx - 遍历 Json

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:39 25 4
gpt4 key购买 nike

我正在使用 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 既不提供到迭代器的转换也不提供对“!=”运算符的覆盖。

最佳答案

But jsonxx doesn't provide neither conversion to iterator nor override for "!=" operator.

这是一个误解。没必要 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*>&

Signature as seen in the header:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com