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",

},
相关推荐
木子.李3474 小时前
排序算法总结(C++)
c++·算法·排序算法
freyazzr5 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++
fpcc6 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
终焉代码6 小时前
STL解析——list的使用
开发语言·c++
DevangLic6 小时前
【 *p取出内容 &a得到地址】
c++
鑫鑫向栄7 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划
鑫鑫向栄7 小时前
[蓝桥杯]带分数
数据结构·c++·算法·职场和发展·蓝桥杯
m0_552200827 小时前
《UE5_C++多人TPS完整教程》学习笔记37 ——《P38 变量复制(Variable Replication)》
c++·游戏·ue5
小wanga7 小时前
【递归、搜索与回溯】专题三 穷举vs暴搜vs回溯vs剪枝
c++·算法·机器学习·剪枝
Code_流苏8 小时前
C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)
开发语言·c++·stl容器·课设·期末大作业·日历程序·面向对象设计