RapidJSON库通过索引在数组中获取值

Gre*_*ego 11 c c++ json

{"hi": "hellow",
"first":
    {"next":[
            {"key":"important_value"}
        ]
    }

}
Run Code Online (Sandbox Code Playgroud)

在数组中访问RapidJSON:

这工作:cout << "HI VALUE:" << variable["hi"].GetString() << endl;这将输出:hellow正如预期的那样,问题是访问内部值,如果我想得到"Important_Value",我尝试过这样的事情:cout << "Key VALUE:" << variable["first"]["next"][0]["key"].GetString() << endl ;但是这不起作用,我希望能够获得"important_value" "通过数组的第一项,在这种情况下,[0]这是导致错误.

如何通过索引获取它?我希望我的解释清楚.

提前致谢.

mol*_*a10 21

JSON

    {"hi": "hellow", "first":  {"next":[{"key":"important_value"}  ] } }
Run Code Online (Sandbox Code Playgroud)

码:

rapidjson::Document document;       

if (document.Parse<0>(json).HasParseError() == false)
{
    const Value& a = document["first"];

    const Value& b = a["next"];

    // rapidjson uses SizeType instead of size_t.
    for (rapidjson::SizeType i = 0; i < b.Size(); i++)
    {
        const Value& c = b[i];

        printf("%s \n",c["key"].GetString());
    }        
}
Run Code Online (Sandbox Code Playgroud)

将打印important_value

  • 这不能回答任何问题,用括号 [] 举例说明我的例子,括号是问题,因为它是数组的自动位置,第一个是 0,下一个是 1 等等......确实,我已经有了,尝试获取我的示例中的值,使用相同的来源。 (2认同)

Mil*_*Yip 13

[更新]

通过贡献者的聪明工作,RapidJSON现在可以消除0字符串中的字面值.所以问题不再发生.

https://github.com/miloyip/rapidjson/issues/167


问题,正如mjean指出的那样,编译器无法通过升级来确定它是应该调用对象成员访问器还是数组元素访问器0:

GenericValue& operator[](const Ch* name)
GenericValue& operator[](SizeType index)
Run Code Online (Sandbox Code Playgroud)

使用[0u][SizeType(0)]可以解决此问题.

处理此问题的另一种方法是停止使用operator []的重载版本.例如,operator()用于一种类型的访问.或使用正常的功能,例如GetMember(),GetElement().但我现在对此没有偏好.其他建议是受欢迎的.