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

},
相关推荐
迷迭所归处4 分钟前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林34 分钟前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice1 小时前
2024.9.19
c++
天玑y1 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2332 小时前
c++ static(详解)
开发语言·c++
菜菜想进步2 小时前
内存管理(C++版)
c语言·开发语言·c++
Joker100852 小时前
C++初阶学习——探索STL奥秘——模拟实现list类
c++
科研小白_d.s2 小时前
vscode配置c/c++环境
c语言·c++·vscode
湫兮之风2 小时前
c++:tinyxml2如何存储二叉树
开发语言·数据结构·c++
友友马3 小时前
『 Linux 』HTTP(一)
linux·运维·服务器·网络·c++·tcp/ip·http