在C++中使用 RapidJSON 访问 JSON 数组的字段
Access fields of a JSON array using RapidJSON in C++
我是使用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()
获取迭代器。
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- 使用 Qt 解析 JSON 数组
- 在 C++ 中访问 JSON 数组值
- 无法使用 Poco 库正确克隆 JSON 数组C++
- 获取嵌套的 JSON 数组和矩阵C++
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- JSONCPP 只用一个元素写入 JSON 数组
- 如何打印 JSON 数组
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 从QT的Web服务中解析未命名的JSON数组
- 使用 boost 读取复杂的 JSON 数组
- 创建 Qstring 的 Json 数组
- 在 qt c++ 中获取 Json 数组中 Qstring 的输出
- 如何使用 QT 创建 JSON 数组
- 如何将JSON数组存储在Arduino程序中
- C 返回函数的函数返回JSON数组通过Nlohmann Json.hpp
- 使用Boost C 创建JSON数组
- 从 JSON 数组获取天气
- 使用JSONCPP创建空的JSON数组
- C++ 将请求发送到 Web 服务器上的 API,然后接收 JSON 数组响应