【问题标题】:Create JSON array of strings with jsoncpp使用 jsoncpp 创建 JSON 字符串数组
【发布时间】:2013-09-24 10:45:09
【问题描述】:

在将新文件写入磁盘时,我需要更新索引(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,一切似乎都正常,但数组始终为空。

【问题讨论】:

    标签: c++ arrays json jsoncpp


    【解决方案1】:

    问题出现在这里:

    elements = root[type];
    

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

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

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

    root[type].append(name.c_str());
    

    【讨论】:

    • 或者只是让elements成为一个指针:Value* element; if (...) element = &amp;root[type]; ...。
    猜你喜欢
    • 2012-10-28
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多