nlohmann 库是用来解析 json 的库,只有一个 json.hpp 文件, 个人比较喜欢用。
以下是我的使用方式
1. json结点与结构体定义“一一对应”,并为每个结构体声明对应的 from_json 和 to_json 函数。
示例 json 说明:
example 节点对应代码中的 stConfig 结构体. example ;子结点 fileAttribute 为一个数组对应结构体中的 vector 变量, 数组内容对应结构体 stArrayItem, 其内部还有一个字符串数组 localDir.
{
"example": {
"name": "example",
"enable": false,
"sockBufferSize": 204800,
"fileAttribute": [
{
"deleteFile": false,
"localDir": [
"/mnt/d/Data/Dir1",
"/mnt/d/Data/Dir2"
],
"subDir": false
}
]
}
}
/*
* example.h 文件
*/
struct stArrayItem
{
bool bSubDir = false;
bool bDeleteFile = true;
std::vector<std::string> vecLocalDir;
};
// json 填充函数
void from_json(const nlohmann::json &j, stArrayItem &v);
void to_json(nlohmann::json &j, const stArrayItem &v);
// 运行信息
struct stConfig
{
bool bEnable = false; // 链路可用
std::string strName;
// socket数据缓冲区大小
unsigned int uiSockBufferSize = 4096;
std::vector<stArrayItem> vecArray;
};
// json 填充函数
void from_json(const nlohmann::json &j, stConfig &v);
void to_json(nlohmann::json &j, const stConfig &v);
实现 json 的 填充和读取函数
/*
* example.cpp 文件
*/
#include "example.h"
//json 填充函数
void from_json(const nlohmann::json& j, stArrayItem& v)
{
j.at("deleteFile").get_to(v.bDeleteFile);
j.at("localDir").get_to(v.vecLocalDir);
if (j.contains("subDir"))
{
j.at("subDir").get_to(v.bSubDir);
}
}
void to_json(nlohmann::json& j, const stArrayItem& v)
{
j = nlohmann::json{
{"deleteFile",v.bDeleteFile},
{"localDir",v.vecLocalDir},
{"subDir",v.bSubDir}
};
}
//json 填充函数
void from_json(const nlohmann::json& j, stConfig& v)
{
j.at("enable").get_to(v.bEnable);
j.at("name").get_to(v.strName);
j.at("sockBufferSize").get_to(v.uiSockBufferSize);
if (j.contains("fileAttribute"))
{
j.at("fileAttribute").get_to(v.vecArray);
}
}
void to_json(nlohmann::json& j, const stConfig& v)
{
j = nlohmann::json{
{"enable",v.bEnable},
{"sockBufferSize",v.uiSockBufferSize},
{"name",v.strName},
{"fileAttribute",v.vecArray}
};
}
json 文件解析文件时会自动调用对应的 from_json 函数。
// 定义存储对象
stConfig g_stConfigExample;
/**
* @brief loadCfgFile 从指定配置文件加载配置项
* @author
* @date
* @param strCfgFilePath
* @return bool
*/
bool loadCfgFile(const std::string& strCfgFile)
{
LOGI("load Config file " + strCfgFile);
std::ifstream jsonStream(strCfgFile);//打开文件,关联到流in
if (!jsonStream.is_open())
{
return false;
}
nlohmann::json jsonCfg;
jsonStream >> jsonCfg;
jsonStream.close();
std::string strTip;
if (jsonCfg.contains("tip"))
{
jsonCfg["tip"].get_to(strTip);
}
if (jsonCfg.contains("example"))
{
jsonCfg["example"].get_to(g_stConfigExample);
}
return true;
}
to_json 有时间再补