0

这是我的json:

{
    "data": {
        "text": "hey stackoverflow",
        "array_1": [
            ["hello", "world", 11, 14]
        ]
    },
}

我设法text像这样提取属性:

代码:

document.Parse(request_body);

auto& data = document["data"];

std::string text = data["text"].GetString();
printf("text: %s\n", text.c_str());

输出:

text: hey stackoverflow

现在我需要提取array_1std::vector<std::vector<std::any>>.

我想,要拥有这样的数据类型,我将不得不迭代data["array_1"]使用 rapidjson 的类型来填充向量。

问题是,即使尝试复制我在互联网上看到的内容,我仍然无法读取里面的值data["array_1"]

代码:

auto& array_1 = data["array_1"];
static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };

for (rapidjson::Value::ConstValueIterator itr = array_1.Begin(); itr != array_1.End(); ++itr){
    printf("item\n");
    for (rapidjson::Value::ConstValueIterator itr2 = itr->Begin(); itr2 != itr->End(); ++itr2){
        printf("Type is %s\n", kTypeNames[itr->GetType()]);
    }
}

输出:

item
Type is Array
Type is Array
Type is Array
Type is Array

但我需要:

item
Type is String
Type is String
Type is Number
Type is Number

编辑

我在错误的迭代器上调用了GetType..

谢谢您的帮助

4

1 回答 1

1
    printf("Type is %s\n", kTypeNames[itr2->GetType()]);

不是

    printf("Type is %s\n", kTypeNames[itr->GetType()]);

您正在打印出 的类型item,也就是["hello", "world", 11, 14],而不是["hello", "world", 11, 14]重复的元素。

或者:

for (auto&& item : array_1.GetArray()) {
  printf("item\n");
  for (auto&& elem : item.GetArray()){
    printf("Type is %s\n", kTypeNames[elem.GetType()]);
  }
}

摆脱一些迭代噪音。(需要和 rapidJson v1.1.0)

于 2019-10-28T17:06:09.090 回答