You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定颜色JSON转换为std::map<CString,CString>?有无更优实现方式?

如何将颜色JSON数组便捷转换为std::map<CString,CString>

问题描述

手里有一份包含颜色十六进制码(#xxxxxx格式)和对应名称的JSON数组,需要转换成std::map<CString,CString>,用于通过十六进制码快速查询颜色名称来生成HTML内容。已知可手动逐个调用map.emplace(L"#ff0000", L"red");添加元素,但这种方式过于繁琐,寻求更简便的实现方法。


解决方案

方案1:使用JSON解析库自动转换

如果项目已集成JSON解析库(比如nlohmann/json,单头文件库,集成成本低),可直接解析JSON数组并遍历填充map。

假设JSON结构如下:

[
  {"code": "#ff0000", "name": "red"},
  {"code": "#00ff00", "name": "green"},
  {"code": "#0000ff", "name": "blue"}
]

代码实现:

#include <nlohmann/json.hpp>
#include <map>
#include <atlstr.h> // 引入CString定义

using json = nlohmann::json;

std::map<CString, CString> ColorJsonToMap(const json& colorJson) {
    std::map<CString, CString> colorMap;
    for (const auto& item : colorJson) {
        // 将std::string转换为CString
        CString code(item["code"].get<std::string>().c_str());
        CString name(item["name"].get<std::string>().c_str());
        colorMap.emplace(std::move(code), std::move(name));
    }
    return colorMap;
}

若JSON为宽字符格式,可使用nlohmann/json的宽字符版本,直接转换更便捷:

// 定义宽字符JSON类型
using json = nlohmann::basic_json<std::map, std::vector, std::wstring, bool, int64_t, uint64_t, double, std::allocator, nlohmann::adl_serializer>;

// 解析后直接提取std::wstring转CString
CString code(item["code"].get<std::wstring>().c_str());
CString name(item["name"].get<std::wstring>().c_str());

方案2:编译期批量初始化map

如果颜色列表固定不变,无需运行时解析JSON,可利用C++11及以上的初始化列表批量构建map,比逐个调用emplace简洁高效:

#include <map>
#include <atlstr.h>

// 编译期完成初始化,运行时直接使用
const std::map<CString, CString> colorMap = {
    {L"#ff0000", L"red"},
    {L"#00ff00", L"green"},
    {L"#0000ff", L"blue"},
    // 依次添加其他颜色条目...
};

方案3:自定义批量导入工具函数

若JSON存储在本地文件或资源中,可封装工具函数读取并解析,避免重复编写解析逻辑:

#include <fstream>
#include <nlohmann/json.hpp>
#include <map>
#include <atlstr.h>

using json = nlohmann::json;

std::map<CString, CString> LoadColorMapFromFile(const std::wstring& filePath) {
    std::map<CString, CString> colorMap;
    std::ifstream file(filePath);
    if (!file.is_open()) {
        // 处理文件打开失败的异常逻辑
        return colorMap;
    }

    json colorJson;
    file >> colorJson;

    for (const auto& item : colorJson) {
        CString code(item["code"].get<std::string>().c_str());
        CString name(item["name"].get<std::string>().c_str());
        colorMap.emplace(std::move(code), std::move(name));
    }

    return colorMap;
}

调用示例:

// 从本地JSON文件加载颜色映射
auto myColorMap = LoadColorMapFromFile(L"./colors.json");

内容的提问来源于stack exchange,提问作者Andrew Truckle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:12:37