c++ json 库 nlohmann json 转换异常 [json.exception.type_error.305]

需求 nlohmman 进行 json 转换时,报异常: [json.exception.type_error.305] cannot use operator[] with a string argument with array. 解决 转换为 json 异常 原因可能是,嵌套时,括号不匹配 void to_json(json& j, const VoltageConfigJson& config) { j = json{{"config_name", config.name}}; for (auto & cfg : config.data) { json channel; to_json(channel, cfg); j["config_data"].push_back(channel); } } 上面这个代码中,如果第一句写成下面这样,那么就会是 305 的异常。 j = json{"config_name", config.name}; 参考 {json.exception.type_error.305} cannot use operator{} with a string argument with array Cannot use operator{} with a string argument with string...

2023-06-26 · 1 min · 92 words · RamLife

c++ json 库 nlohmann 中类和 json 转换

需求 尝试使用 nlohmman 把复杂的类转为 json。 解决 复杂的类需要对其中的某些部分单独抽出来进行转换。 用于转换为 json 的类 struct VoltageSetConfigData { float w1; float p1; float w2; float p2; float ref; float pf; }; using VoltageGetConfigData = VoltageSetConfigData; class VoltageConfigJson { public: std::string name; std::vector<VoltageGetConfigData> data; }; 数组单个元素转换 void to_json(json& j, const VoltageGetConfigData& data) { j = json{{"w1", data.w1}, {"p1", data.p1}, {"w2", data.w2}, {"p2", data.p2}, {"ref", data.ref}, {"pf", data.pf}}; } void from_json(const json& j, VoltageGetConfigData& data) { j.at("w1").get_to(data.w1); j....

2023-06-26 · 1 min · 135 words · RamLife

c++ json 库 nlohmann 文件读写

需求 nlohmman 读写 json 配置文件. 解决 写文件 QString fileName = QFileDialog::getSaveFileName(this, tr("save config file"), "./voltage_", tr("Json (*.json)")); qDebug() << fileName << Qt::endl; if (fileName.isEmpty()) return; ofstream file(fileName.toStdString(), ios::out); json j; to_json(j, config_json); file << j << std::endl; 读文件 QString file_name = QFileDialog::getOpenFileName(this, tr("load config file"), "./voltage_", tr("Json (*.json)")); qDebug() << file_name << Qt::endl; if (file_name.isEmpty()) return; ifstream file(file_name.toStdString(), ios::in); json j = json::parse(file); 参考 nlohmann/json 的主要用法 【C++ JSON 开源库】nlohmann入门使用总结 nlohmann/json...

2023-06-26 · 1 min · 72 words · RamLife