[C++] 使用 nlohmann 加载 json 内容

本文介绍了如何使用nlohmann库解析JSON配置文件,通过定义结构体与JSON键一一对应,并实现from_json和to_json函数,以便于读取和写入JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 有时间再补

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值