0

我有一个包含 json 数据的“jvalue”变量:

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

我知道我在这里遗漏了一些东西,但这个想法不会出现在我的脑海中。也许像双循环一样。

任何人都可以分享一个想法。谢谢你。

4

1 回答 1

3

现在你只迭代对象的属性,你也必须迭代数组元素:

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;
    }
}
于 2018-04-30T08:04:27.617 回答