初始化RapidJSON解析器:使用
rapidjson::Document
对象创建解析器,并调用
Parse()
方法来读取JSON字符串,解析器将自动将字符串解析成JSON对象结构。
获取JSON数组:使用
rapidjson::Document
对象中的
GetArray()
方法来获取JSON数组中的值,此方法返回一个
rapidjson::Value
类型的对象。
遍历JSON数组:使用
rapidjson::Value
对象中的
Size()
和
operator[]
方法来遍历JSON数组中的每个值。
以下是一个简单的C++代码示例,演示如何使用RapidJSON解析JSON数组:
#include "rapidjson/document.h"
#include <iostream>
#include <string>
using namespace rapidjson;
using namespace std;
int main() {
string json = "[\"Hello\", \"World\"]";
Document doc;
doc.Parse(json.c_str());
Value& arr = doc;
for (SizeType i = 0; i < arr.Size(); i++) {
cout << arr[i].GetString() << endl;
return 0;
在这个代码示例中,我们首先定义了一个JSON数组字符串 json
。然后使用 Document
对象创建了一个解析器,并调用 Parse()
方法解析JSON字符串。我们通过 doc
对象获取了JSON数组 arr
,并使用for循环遍历数组中的每个值。最后,我们打印出每个值的字符串形式。
希望这个代码示例可以帮助你更好地理解如何使用RapidJSON解析JSON数组。