我一直在尝试解析一个JSON字符串,它看起来像:
[1, 2, 3, 4]
这是我的代码:
#include <iostream>
#include "rapidjson/document.h"
void main()
{
char const *json_str = "[1, 2, 3, 4]";
rapidjson::Document d;
d.Parse(json_str);
// Ninja edit to fix json_str.IsArray()
if(d.IsArray())
{
for(auto &e: d)
{
std::cout << e.GetInt() << std::endl;
}
}
}
不幸的是,由于"begin((未在此范围内声明"和其他同类错误,代码编译失败
这表明我正在尝试迭代一些不能调用std::begin((和std::end((的东西
这里的rapidjson教程只解释了如何迭代使用GetArray((检索的数组,而不是在文档级别。我还浏览了文档,在谷歌上搜索,运气不太好。我还尝试过使用:
for(auto &e: document.GetArray()) // Similar to the tutorial's code, which calls d.GetObject()
但这并不能说明GenericDocument(Document是一个typedef,AFAIK(没有名为GetArray((的成员。因此,它也没有GetObject((成员。
另一方面,使用计数器进行迭代也很好。
我可能错过了一些显而易见的东西,因为这是漫长的一天,而在我所在的地方,现在是凌晨12:00,但我真的很感激能为我指出哪里可能出错,以及如何完成这项任务。
d.GetArray()
是将文档强制转换为数组的正确方法。
但是,在您的示例中,您对输入字符串而不是Document
实例调用IsArray()
。
以下代码适用于我:
#include <iostream>
#include <rapidjson/document.h>
int main() {
char const* json_str = "[1, 2, 3, 4]";
rapidjson::Document d;
d.Parse(json_str);
if (d.IsArray())
{
for (auto& e : d.GetArray())
{
std::cout << e.GetInt() << std::endl;
}
}
}
输出:
1
2
3
4