RapidJSON 库通过索引获取数组中的值
RapidJSON library getting a value inside an array by its index
{"hi": "hellow",
"first":
{"next":[
{"key":"important_value"}
]
}
}
在数组中访问 RapidJSON:
这有效: cout << "HI VALUE:" << variable["hi"].GetString() << endl;
这将输出: hellow
正如预期的那样,问题是访问内部值,例如如果我想获得"Important_Value",我尝试了这样的事情: cout << "Key VALUE:" << variable["first"]["next"][0]["key"].GetString() << endl ;
但这不起作用,我希望能够通过数组的第一项获取"important_value",在这种情况下,是[0]
导致错误。
如何通过索引获取它?我希望我的解释很清楚。
提前谢谢。
{"hi": "hellow", "first": {"next":[{"key":"important_value"} ] } }
法典:
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());
}
}
将打印important_value
[更新]
通过贡献者的聪明工作,RapidJSON 现在可以消除字符串中的文字0
歧义。所以问题不再发生。
https://github.com/miloyip/rapidjson/issues/167
正如 mjean 指出的那样,这个问题是编译器无法通过文字0
确定它应该调用对象成员访问器还是数组元素访问器:
GenericValue& operator[](const Ch* name)
GenericValue& operator[](SizeType index)
使用 [0u]
或 [SizeType(0)]
可以解决此问题。
解决此问题的另一种方法是停止对 operator[] 使用重载版本。例如,将operator()
用于一种类型的访问。或者使用正常函数,例如GetMember()
、GetElement()
。但我现在对此没有偏好。欢迎其他建议。
我在教程.cpp文件中注意到了这一点;
// Note:
//int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
int z = a[0u].GetInt(); // This works too.
我没有测试它,但您可能想尝试其中之一;
变量["第一个"]["下一个"][0u]["键"]。GetString()
变量["第一"]["下一个"][大小类型(0)]["键"]。GetString()
auto value = my_array[rapidjson::SizeType(index)].GetFoo();
// replace GetFoo with the type of element you are retrieving, e.g. GetString, GetObject
使用括号访问它,则可以使用以下方法:
int i=0;
cout<<"Key VALUE:"<<variable["first"]["next"][i]["key"].GetString()<<endl ;
输出:键值:important_value
它对我有用。
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 使用指针从C++中的数组中获取最大值
- 获取字符串的长度并将其分配给数组
- 数组长度,为什么从命令行获取时不能使用它?
- 如何在 nlohmann 的 json 库中获取数组长度?
- 在c++中获取两个大int,并将它们存储在数组中
- 如何在C++中获取二维数组中最少的一列数?
- 从 numpy 数组获取指针以将图像发送到C++
- 指针数组.获取指针元素的值
- 循环以使用 cstring 数组 c++ 获取用户输入
- 一种从元组/数组获取参数包的方法
- 如何使用数组获取输入,并将其存储在record.h类的主类中的变量中
- 如何使用数组获取命令行参数
- 从 JSON 数组获取天气
- 布尔数组获取意外的默认值
- 填充列表<>使用数组获取错误的数字
- 如何在C++中为矢量数据结构中的二维数组获取用户输入,而不使用行和列上的两个for循环
- 在自定义库中操作2d C++数组-获取行数
- 使用数组获取测试结果
- 数组c++获取值