简体   繁体   English

如何使用 rapidjson 从 object 内部解析 JSON 数组

[英]How to parse JSON array from inside an object with rapidjson

The following is a JSON file exported from Tiled Map Editor.以下是从 Tiled Map 编辑器导出的 JSON 文件。

{ "compressionlevel":-1,
 "height":32,
 "infinite":false,
 "layers":[
        {
         "data":[ A whole bunch of integers in here],
         "height":32,
         "id":1,
         "name":"Tile Layer 1",
         "opacity":1,
         "type":"tilelayer",
         "visible":true,
         "width":32,
         "x":0,
         "y":0
        }],
 "nextlayerid":2,
 "nextobjectid":1,
 "orientation":"orthogonal",
 "renderorder":"right-down",
 "tiledversion":"1.7.2",
 "tileheight":32,
 "tilesets":[
        {
         "firstgid":1,
         "source":"..\/..\/..\/..\/Desktop\/tileset001.tsx"
        }],
 "tilewidth":32,
 "type":"map",
 "version":"1.6",
 "width":32
}

And in this C++ block I am trying to parse out the data I actually need.在这个 C++ 块中,我试图解析出我实际需要的数据。

std::ifstream inFStream(filePath, std::ios::in);
    if(!inFStream.is_open())
    {
        printf("Failed to open map file: &s", filePath);
    }

    rapidjson::IStreamWrapper inFStreamWrapper{inFStream};
    rapidjson::Document doc{};
    doc.ParseStream(inFStreamWrapper);

    _WIDTH = doc["width"].GetInt();   //get width of map in tiles
    _HEIGHT = doc["height"].GetInt(); //get height of map in tiles

    const rapidjson::Value& data = doc["layers"]["data"]; //FAILURE POINT
    assert(data.IsArray());

When I compile I am able to extract the right value for width and height which are outside of "layers":[{}] But when that const rapidjson::Value& data = doc["layers"]["data"];当我编译时,我能够提取"layers":[{}]但是当const rapidjson::Value& data = doc["layers"]["data"]; gets called I get a runtime error claiming that document.h line 1344 IsObject() Assertion Failed.被调用我收到一个运行时错误,声称 document.h 第 1344 行IsObject()断言失败。

Ive been up and down the rapidjson website and other resources and cant find anything quite like this.我一直在 rapidjson 网站和其他资源上上下下,找不到类似的东西。

The next step would be to get the int values stored in "data" and push them into a std::vector but thats not going to happen till I figure out how to get access to "data"下一步是获取存储在“数据”中的 int 值并将它们推送到std::vector中,但在我弄清楚如何访问“数据”之前,这不会发生

doc['layers'] is an array. doc['layers']是一个数组。

const rapidjson::Value& layers = doc["layers"];
assert(layers.IsArray()); 

for (size_t i=0; i < layers.Size(); i++) {
  const rapidjson::Value& data = doc["layers"][i]["data"];
  assert(data.IsArray());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM