据我了解,这个 char* 是一个有效的 json 字符串。
const char* json = { "array":[14, -15, 3.17], "array_type": ["uint", "int", "float"] }
数组中的所有数字应为 4 个字节。
如何使用 rapidjson 循环遍历数组?
到目前为止,这是我的代码:
#include "rapidjson/document.h"
using namespace rapidjson;
int main(void)
{
int i_val; unsigned int ui_val; float f_val;
const char* json = "{ \"array\":[14, -15, 3.17], \"array_type\" : [\"uint\", \"int\", \"float\"] }";
Document d;
d.Parse<0>(json);
Value& a = d["array"];
Value& at = d["array_type"];
for (SizeType i = 0; i<a.Size(); i++)
{
if (a[i].IsInt() && (std::string)at[i].GetString() == "int")
{
i_val = a[i].GetInt();
//Do anything
}
if (a[i].IsUint() && (std::string)at[i].GetString() == "uint")
{
ui_val = a[i].GetUint();
//Do anything
}
if (a[i].IsDouble() && (std::string)at[i].GetString() == "float")
{
f_val = (float)a[i].GetDouble();
//Do anything
}
}//end for
return 0;
}
错误:
TestApp: /workspace/TestApp/src/include/rapidjson/document.h:1277: rapidjson::GenericValue<Encoding, Allocator>& rapidjson::GenericValue<Encoding, Allocator>::operator[](rapidjson::SizeType) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; rapidjson::SizeType = unsigned int]: Assertion `index < data_.a.size' failed.
代码在函数 a.Size() 处崩溃,当它在 GetDouble 之后执行时。怎么能解决这个问题?
我知道最后一个“如果”是错误的,这可能就是程序崩溃的原因。Double 为 8 个字节,SizeType 默认为 4 个字节。
是否有解决方案来循环数组?如果不是,我也会对其他库很好。我需要通过 json 传输这三种不同类型的值。顺便说一下,数组的长度可以是 1 到 500。
(没有 GetFloat() 函数。)
感谢您提供任何帮助。问候