我需要在将新文件写入磁盘时更新索引(JSON 格式),并且由于文件已分类,所以我正在使用具有这种结构的对象:
{ "type_1" : [ "file_1", "file_2" ], "type_2" : [ "file_3", "file_4" ] }
我认为这对于 jsoncpp 来说是一项简单的任务,但我可能遗漏了一些东西。
我的代码(简化版)在这里:
std::ifstream idx_i(_index.c_str());
Json::Value root;
Json::Value elements;
if (!idx_i.good()) { // probably doesn't exist
root[type] = elements = Json::arrayValue;
} else {
Json::Reader reader;
reader.parse(idx_i, root, false);
elements = root[type];
if (elements.isNull()) {
root[type] = elements = Json::arrayValue;
}
idx_i.close();
}
elements.append(name.c_str()); // <--- HERE LIES THE PROBLEM!!!
std::ofstream idx_o(_index.c_str());
if (idx_o.good()) {
idx_o << root;
idx_o.close();
} else {
Log_ERR << "I/O error, can't write index " << _index << std::endl;
}
所以,我正在打开文件,读取 JSON 数据有效,如果找不到,我会创建一个新数组,问题是:当我尝试向数组附加一个值时,它没有工作,数组保持为空,并写入文件。
{ "type_1" : [], "type_2" : [] }
尝试调试我的代码,并调用 jsoncpp,一切似乎都正常,但数组始终为空。
最佳答案
问题出现在这里:
elements = root[type];
因为您在调用此 JsonCpp API 时正在创建 root[type]
的拷贝:
Value &Value::operator[]( const std::string &key )
因此根本不修改 root
文档。避免此问题的最简单方法是,在您的情况下,不使用 elements
变量:
root[type].append(name.c_str());
关于c++ - 使用 jsoncpp 创建 JSON 字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18893157/