需求

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

{json.exception.type_error.305} cannot use operator{} with a string argument with string

nlohmann::json组包报错:{type_error.305} cannot use operator{} with a string argument with array