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

RapidJSON library getting a value inside an array by its index

本文关键字:数组 获取 索引 RapidJSON      更新时间:2023-10-16
{"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]导致错误。

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

提前谢谢。

JSON

    {"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

它对我有用。