使用 jsoncpp 创建字符串的 JSON 数组
Create JSON array of strings with jsoncpp
在将新文件写入磁盘时,我需要更新索引(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());
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- 使用 Qt 解析 JSON 数组
- 在 C++ 中访问 JSON 数组值
- 无法使用 Poco 库正确克隆 JSON 数组C++
- 获取嵌套的 JSON 数组和矩阵C++
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- JSONCPP 只用一个元素写入 JSON 数组
- 如何打印 JSON 数组
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 从QT的Web服务中解析未命名的JSON数组
- 使用 boost 读取复杂的 JSON 数组
- 创建 Qstring 的 Json 数组
- 在 qt c++ 中获取 Json 数组中 Qstring 的输出
- 如何使用 QT 创建 JSON 数组
- 如何将JSON数组存储在Arduino程序中
- C 返回函数的函数返回JSON数组通过Nlohmann Json.hpp
- 使用Boost C 创建JSON数组
- 从 JSON 数组获取天气
- 使用JSONCPP创建空的JSON数组
- C++ 将请求发送到 Web 服务器上的 API,然后接收 JSON 数组响应