我有一个" jvalue"包含json数据的变量:
{
"data": [
{
"_id": 123,
"name": "Name 1"
},
{
"_id": 124,
"name": "Name 2"
}
],
"success": true
}
这是我尝试过的代码:
auto data = jvalue.at(U("data")).at(0);
auto dataObj = data.as_object();
for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;
std::wcout << "Property: " << propertyName << ", Value: " << propertyValue << std::endl;
}
但它只显示第一组数据:
Property: _id, Value: 123
Property: name, Value: "Name 1"
我知道我在这里遗漏了一些东西,但这个想法不会出现在我脑海中。 也许就像双循环一样。
任何人都可以分享这个想法。谢谢。
答案 0 :(得分:2)
现在只迭代对象的属性,你也必须迭代数组元素:
auto DataArray = jvalue.at(U("data")).as_array();
for (int i = 0; i< DataArray.size(); i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;
std::wcout << "Property: " << propertyName << ", Value: " <<
propertyValue << std::endl;
}
}
或使用迭代器迭代数组:
auto DataArray = jvalue.at(U("data")).as_array();
for (auto Iter = DataArray.begin(); Iter != DataArray.end(); ++Iter)
{
auto& data = *Iter;
auto dataObj = data.as_object();
for (auto iterInner = dataObj.cbegin(); iterInner != dataObj.cend(); ++iterInner)
{
auto &propertyName = iterInner->first;
auto &propertyValue = iterInner->second;
std::wcout << "Property: " << propertyName << ", Value: " <<
propertyValue << std::endl;
}
}