定义
#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();
}