使用jsoncpp创建字符串的JSON数组

G B*_*G B 8 c++ arrays json jsoncpp

我需要在将新文件写入磁盘时更新索引(采用JSON格式),并且由于文件是分类的,我使用的是具有这种结构的对象:

{ "type_1" : [ "file_1", "file_2" ], "type_2" : [ "file_3", "file_4" ] }
Run Code Online (Sandbox Code Playgroud)

我认为这对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;
}
Run Code Online (Sandbox Code Playgroud)

所以,我打开文件,读取JSON数据工作,如果我找不到任何,我创建一个新数组,问题是:当我尝试向数组追加一个值时,它不起作用,数组保持为空,并写入文件.

{ "type_1" : [], "type_2" : [] }
Run Code Online (Sandbox Code Playgroud)

试图调试我的代码和jsoncpp调用,一切似乎都没问题,但数组总是空的.

Sga*_*Sga 6

问题出现在这里:

elements = root[type];
Run Code Online (Sandbox Code Playgroud)

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

Value &Value::operator[]( const std::string &key )
Run Code Online (Sandbox Code Playgroud)

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

root[type].append(name.c_str());
Run Code Online (Sandbox Code Playgroud)