jeson配置文件字典

这是c++17的用法:

#include

#include <unordered_map>

#include

#include

#include <nlohmann/json.hpp>

// 使用nlohmann/json库

using json = nlohmann::json;

// 存储设备类型和单板类型的映射

std::unordered_map<int, std::string> deviceTypeMap;

std::unordered_map<int, std::string> boardTypeMap;

std::unordered_map<int, int> deviceIdentifierMap;

// 从配置文件中加载映射

void loadConfiguration(const std::string& configFile) {

std::ifstream file(configFile);

json config;

file >> config;

复制代码
for (auto& [key, value] : config["deviceTypes"].items()) {
    int intKey = std::stoi(key, nullptr, 16);
    deviceTypeMap[intKey] = value["name"];
    deviceIdentifierMap[intKey] = value["identifier"];
}
for (auto& [key, value] : config["boardTypes"].items()) {
    int intKey = std::stoi(key, nullptr, 16);
    boardTypeMap[intKey] = value;
}

}

// 解析MAC地址

void parseMacAddress(const std::string& mac) {

// 删除'-'分隔符

std::string macNoDash = mac;

macNoDash.erase(std::remove(macNoDash.begin(), macNoDash.end(), '-'), macNoDash.end());

复制代码
// 提取MAC地址中的字节
int byte1 = std::stoi(macNoDash.substr(0, 2), nullptr, 16);
int byte2 = std::stoi(macNoDash.substr(2, 2), nullptr, 16);
int byte3 = std::stoi(macNoDash.substr(4, 2), nullptr, 16);
int byte4 = std::stoi(macNoDash.substr(6, 2), nullptr, 16);
int byte5 = std::stoi(macNoDash.substr(8, 2), nullptr, 16);
int byte6 = std::stoi(macNoDash.substr(10, 2), nullptr, 16);

// 查找设备类型和标识符
std::string deviceType = deviceTypeMap[byte2];
int identifier = deviceIdentifierMap[byte2];
std::string boardType = boardTypeMap[byte5];

// 输出解析结果
std::cout << ": " << deviceType << std::endl;
std::cout << ": " << identifier << std::endl;
std::cout << ": " << byte4 << "槽" << std::endl;
std::cout << ": " << boardType << std::endl;
std::cout << ": " << byte6 << "口" << std::endl;

}

int main() {

// 从配置文件加载映射

loadConfiguration("config.json");

复制代码
// 示例MAC地址
std::string macAddress = "1234-3333-4566";

// 解析MAC地址
parseMacAddress(macAddress);

return 0;

}

配置文件:

"deviceTypes": {

"0x01": {"name": "hhh", "identifier": 1},

"0x02": {"name": "jjj", "identifier": 2},

"0x03": {"name": "hhhh", "identifier": 3},

复制代码
},
"boardTypes": {
    "0x00": "ggg",
    "0x01": "jjj",
    "0x02": "lllll",

},
相关推荐
从零开始的代码生活_2 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
aaPIXa6223 小时前
C++ 用 13 条规则让模型写出安全现代 C++
java·c++·安全
枕星而眠4 小时前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
2601_949817724 小时前
C++指针与引用深度精讲:底层原理、差异对比与高阶实战陷阱
java·jvm·c++
烟锁池塘柳05 小时前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
zh路西法6 小时前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
粘稠的浆糊6 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
誰能久伴不乏6 小时前
C++11 随机数生成——告别 rand()
开发语言·c++
KouFiee6 小时前
同名隐藏基础
开发语言·c++
从零开始的代码生活_7 小时前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法