C++通过json文件配置参数

 一、安装nlohmann json

nlohmann json:安装_nlohmann安装-CSDN博客

依次执行下面指令:

git clone https://gitee.com/cuihongxi/mov_from_github.git

cd json-develop

mkdir build

cd build

cmake ..

make

sudo make install

二、安装完成后使用

#include <nlohmann/json.hpp>

using json = nlohmann::json;

例程:


    // 读取JSON文件
    std::ifstream file("config.json");
    if (!file.is_open()) {
        std::cout << "无法打开JSON文件!" << std::endl;
        return 1;
    }

    // 解析JSON数据
    json data;
    try {
        file >> data;
    } catch (const json::parse_error& e) {
        std::cout << "JSON解析错误:" << e.what() << std::endl;
        return 1;
    }

    // 读取JSON中的参数
    std::string password = data["PASSWORD"];
    std::string account = data["ACCOUNT"];
    std::string com_serial = data["COM"];
    PASSWORD = password.c_str();
    ACCOUNT = account.c_str();
    comName = com_serial.c_str();

JSON

{
    "PASSWORD": "1234",
    "ACCOUNT": "abc",
    "COM": "tty0"
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,您的问题是关于使用Json存储软件配置参数的方法。下面是一个简单的示例: 首先,您需要使用Qt的Json库来读取和写入Json文件。您可以使用QJsonDocument类来解析Json文件。 例如,以下是一个简单的Json文件: ```json { "window_title": "My Application", "window_width": 800, "window_height": 600, "language": "en" } ``` 接下来,您可以使用以下代码来读取Json文件并将其存储在QMap中: ```cpp QFile configFile("config.json"); if(configFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QByteArray data = configFile.readAll(); QJsonDocument document = QJsonDocument::fromJson(data); if(document.isObject()) { QMap<QString, QVariant> configMap = document.toVariant().toMap(); QString title = configMap["window_title"].toString(); int width = configMap["window_width"].toInt(); int height = configMap["window_height"].toInt(); QString language = configMap["language"].toString(); } } ``` 这将创建一个QMap对象,其中包含从Json文件中读取的配置参数。您可以使用这些参数来设置应用程序的设置,例如窗口的标题,大小和语言。 接下来,您可以使用以下代码将配置参数写入Json文件: ```cpp QMap<QString, QVariant> configMap; configMap["window_title"] = "My Application"; configMap["window_width"] = 800; configMap["window_height"] = 600; configMap["language"] = "en"; QJsonDocument document = QJsonDocument::fromVariant(configMap); QFile configFile("config.json"); if(configFile.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&configFile); out << document.toJson(); } ``` 这将创建一个QMap对象,其中包含应用程序的配置参数,并将其转换为QJsonDocument。然后,它会将Json文档写入文件中。 希望这可以帮助您开始使用Json存储软件配置参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

laocui1

你的鼓励是我创作的最大动了

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

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

打赏作者

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

抵扣说明:

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

余额充值