10

在将新文件写入磁盘时,我需要更新索引(以 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 调用,一切似乎都很好,但数组总是空的。

4

1 回答 1

9

问题出现在这里:

elements = root[type];

因为您在调用此 JsonCpp API 时正在创建副本:root[type]

Value &Value::operator[]( const std::string &key )

因此根本不修改root文档。在您的情况下,避免此问题的最简单方法是不使用该elements变量:

root[type].append(name.c_str());
于 2014-03-17T11:24:51.267 回答