在C++中使用 RapidJSON 访问 JSON 数组的字段

Access fields of a JSON array using RapidJSON in C++

本文关键字:JSON 数组 字段 访问 RapidJSON C++      更新时间:2023-10-16

我是使用RapidJSON库的新手,我想知道如何以JSON格式访问数组中的特定元素,这是JSON:

{
"products": [
{
"id_product": 1,
"product_name": "Beer",
"product_price": 120.00
},
{
"id_product": 2,
"product_name": "Pizza",
"product_price": 20.00
}
]
}

我有这部分代码要制作:

Document json_value;
json_value.Parse(json_message); //Above Json
if(!json_value.IsObject())
{
//ERROR
}
if(json_value.HasMember("products"))
{       
const Value& a = json_value["products"];
if(a.IsArray())
{
for (SizeType i = 0; i < a.Size(); i++)
{
//Here i dont know how to access the elements of the array elements, but i need something like this:
int element_id = 1; //id_product = 1
string element_name = "Beer"; // product_name = "Beer"
float element_price = 120.00; //prodcut_price = 120.00
}
}
}

您可以使用operator[]()访问对象的元素。

for (SizeType i = 0; i < a.Size(); i++)
{
if (a[i].IsObject()) {
int element_id = a[i]["id_product"].GetInt();
string element_name = a[i]["product_name"].GetString();
double element_price = a[i]["product_price"].GetDouble();
}
}

请注意,如果您的 JSON 并不总是一致的,您可能需要添加对成员类型和存在的检查。

由于products中的每个"产品"都是一个对象,因此您还可以像这样迭代每个键,值对:

const Value& products = json_value["products"];
for (auto& product: products) {  // products is type Array
for (auto& prod : product.GetObject()) {
std::cout << prod.name  // similar to map->first
// i.e "id_product", "product_name"
<< prod.value // similar to map->second
// i.e 2, "Pizza"
<< std::endl;
}
}

我相信如果值是一个数组,你可以用无符号的int调用operator[]()。本教程似乎证实了这一点:

const Value& a = document["a"];
assert(a.IsArray());
for (SizeType i = 0; i < a.Size(); i++) // Uses SizeType instead of size_t
printf("a[%d] = %dn", i, a[i].GetInt());

您还可以使用MemberBegin()MemberEnd()获取迭代器。