使用rapidjson写入二维vector到JSON文件出现多余嵌套数组求助
问题根源
输出多一层嵌套是因为代码最后做了多余的嵌套操作:你已经把std::vector<std::vector<int>>的两层结构完整写入了globalArray变量,最后又把globalArray作为唯一元素塞进了Document本身的数组中,等于平白多套了一层数组结构。
修改方案
只需要调整给Document赋值的逻辑即可,将原代码中的:
d.SetArray().PushBack(globalArray, allocator);
替换为:
d = globalArray;
仅修改这一行就能得到你预期的两层嵌套数组输出。
修改后完整代码
void resultToJson(std::vector<std::vector<int>> &result, const char *fileName) { rapidjson::Document d; rapidjson::Document::AllocatorType &allocator = d.GetAllocator(); rapidjson::Value globalArray(rapidjson::kArrayType); std::vector<std::vector<int>>::iterator row; for (row = result.begin(); row != result.end(); row++) { std::vector<int>::iterator col; rapidjson::Value myArray(rapidjson::kArrayType); for (col = row->begin(); col != row->end(); col++) { myArray.PushBack(*col, allocator); } globalArray.PushBack(myArray, allocator); } // 仅修改了此处赋值逻辑 d = globalArray; rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); std::ofstream of(fileName); of << buffer.GetString(); if (!of.good()) throw std::runtime_error("Can't write the JSON string to the file!"); }
内容的提问来源于stack exchange,提问作者noman pouigt
相关产品推荐
相关产品推荐

