C++ nlohmann json 使用以及out_of_range.403 解决

定义

#include <nlohmann/json.hpp>

using nlohmann::json;

namespace ns {
    // 首先定义一个结构体
    struct result {
        int res_code;
        std::string res_desc;
    };
    struct person {
        std::string name;
        std::string address;
        int age;
        result result;
    };

    void to_json(json &j, const result &p) {
        j = json{ { "res_code", p.res_code },{ "res_desc", p.res_desc } };
    }

    void from_json(const json& j, result& p) {
        j.at("res_code").get_to(p.res_code);
        j.at("res_desc").get_to(p.res_desc);
    }

    void to_json(json& j, const person& p) {
        j = json{ { "name", p.name },{ "address", p.address },{ "age", p.age } , { "result", p.result } };
    }

    void from_json(const json& j, person& p) {
        j.at("name").get_to(p.name);
        j.at("address").get_to(p.address);
        j.at("age").get_to(p.age);
        j.at("result").get_to(p.result);
    }
} // namespace ns

用法

ns::person p{ “sdfsd”, “sdfsdf”, 54, {0, “ok”} };
json j = p;
std::string str_j = j.dump();
std::cout << str_j.c_str() << std::endl;

json j_c = json::parse(str_j);
ns::person p_c = j_c.getns::person();

补充实用用法,自动生成序列与反序列化代码

如下初始化方式,可以自动生成to_json 和 from_json的方法。避免手动初始化的繁琐过程。

#include <nlohmann/json.hpp>
// define dev callback to js struct
struct ANS {
    std::string Type  ;
    std::string CardID;
    std::string Answer;
};
// generate to_json & from_json
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(ANS, Type, CardID, Answer)
// 或者使用带有默认值的方式
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(ANS, Type, CardID, Answer)

使用时和之前也是一样的

ANS ans;
ans.CardID = "1";
ans.Answer = "A";
nlohmann::json j_ans = ans;
std::string str_ans = j_ans.dump();

403 找不到key的问题处理

如果使用的是NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE则在进行反序列化时,如果结构体中某一项是非必填则很难处理,当前VC2017是没办法正常使用optional进行编译。所以要用NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT这个api去处理结构体。这样不存在的变量就会自动赋予一个默认值。不会抛出out_of_range.403异常了。
https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/
在这里插入图片描述

捕获异常

try{
    nlohmann::json j_ret = nlohmann::json::array();
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        nlohmann::json j_r = nlohmann::json::array();
        for (int i = 0; i < num_cols; i++) {
            std::string col_value = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
            j_r.push_back(col_value);
        }
        j_ret.push_back(j_r);
    }
    ret_str = j_ret.dump();
    spdlog::info("{} :: ret_str is {}.", __FUNCTION__, ret_str);
}
catch (std::exception& e) {
spdlog::error("{} :: catch exception {}.", __FUNCTION__, e.what());
}
catch (...) {
spdlog::error("{} :: catch unkown exception error.", __FUNCTION__);
ret_str = "";
}

解析json数组(sql字符串作为json数组为例)

// SQL batch exec
// 1. parse sqls
nlohmann::json jArray = nlohmann::json::parse(sql);
if (jArray.is_array()) {
    for (const auto& element : jArray) {
    std::string exec_sql = element;
    spdlog::info("{} :: exec sql: {}", __FUNCTION__, exec_sql);
    // SQL exec
    char *zErrMsg = 0;
    rc = sqlite3_exec(dest_db, exec_sql.c_str(), nullptr, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
    spdlog::error("{} :: Error sqlite3_exec: {}", __FUNCTION__, zErrMsg);
    sqlite3_free(zErrMsg);
    ret_bool = false;
    throw std::exception();
    }
    else {
    spdlog::info("{} :: exec part successfully.", __FUNCTION__);
    ret_bool = true;
    }
    }
} else {
    spdlog::error("{} :: Error batch sql is not a json array: {}", __FUNCTION__, sql);
    ret_bool = false;
    throw std::exception();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

frankz61

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值