2017-03-09 257 views
0

我今天早些時候正在測試RapidJSON庫以查看我是否可以使用嵌套值解析文檔,出於某種原因,我無法想出解決方案的錯誤I越來越。我搜索了Google和Stack Overflow一兩個小時,但找不到修復程序。下面是與錯誤一起代碼:斷言`IsArray()'失敗(RapidJSON)

main.cpp中:

#include <iostream> 
#include <SFML/Graphics.hpp> 
#include "rapidjson/document.h" 

#include "include.hpp" 

int main() { 
    unsigned int input = 1; 
    tile output; 
    output = LoadTile("../locations.json", input); 

    std::cout << output.x << std::endl; 

    return 0; 
} 

load.cpp

#include <iostream> 
#include "rapidjson/document.h" 
#include "rapidjson/filereadstream.h" 

#include "include.hpp" 

using namespace rapidjson; 

tile LoadTile(std::string fileName, unsigned int number) { 
    FILE* file = fopen(fileName.c_str(), "r"); 

    char buffer[2048]; 
    FileReadStream stream(file, buffer, 2048); 

    Document doc; 
    doc.ParseStream(stream); 

    tile output; 
    Value& tileNumber = doc[number]; 

    if(!tileNumber.IsObject()) { 
     output.overflow = true; 
     output.x = 0; 
     output.y = 0; 
     output.type = "\0"; 
    }else{ 
     output.x = tileNumber[0]["x"].GetInt(); 
     output.y = tileNumber[0]["y"].GetInt(); 
     output.type = tileNumber[0]["type"].GetString(); 
    } 

    return output; 
} 

include.hpp:

#include <iostream> 
#include <SFML/Graphics.hpp> 
#include "rapidjson/document.h" 

struct tile { 
int x; 
int y; 
std::string type; 
bool overflow = false; 
}; 

tile LoadTile(std::string fileName, unsigned int number); 

的CMakeLists.txt:

cmake_minimum_required(VERSION 2.6) 
project(test) 

set(EXECUTABLE_NAME "test") 
add_executable(${EXECUTABLE_NAME} main.cpp load.cpp include.hpp) 

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH}) 

install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin}) 

locations.json:

{ 
    1:[ 
     {"x":32}, 
     {"y":32}, 
     {"type":"water_c"} 
    ] 
} 

錯誤:

test: /home/.../rapidjson/document.h:1547:rapidjson::GenericValue<Encoding, Allocator>::operator[](rapidjson::SizeType) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; rapidjson::SizeType = unsigned int]: Assertion `IsArray()' failed. 
Aborted (core dumped) 

我知道這是不是JSON格式,我用盡了一切。除非有什麼確實錯了。我在Xubuntu 16.10上運行它。感謝任何能夠提供幫助的人。

回答

0

您的JSON無效。在JSON中,鍵必須是字符串,用雙引號引起來。更多詳情here。 我建議使用JSONLint來驗證JSON字符串。 有效的JSON看起來像這樣(1用雙引號):

{ 
    "1": [{ 
     "x": 32 
    }, { 
     "y": 32 
    }, { 
     "type": "water_c" 
    }] 
}