nlohmann::json 中文乱码解决方案

// UTF8字符串转成GBK字符串
std::string U2G(const std::string& utf8)
{
    int nwLen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
    wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截断字符串 
    memset(pwBuf, 0, nwLen * 2 + 2);

    MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), utf8.length(), pwBuf, nwLen);

    int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

    char* pBuf = new char[nLen + 1];
    memset(pBuf, 0, nLen + 1);

    WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

    std::string retStr = pBuf;

    delete[]pBuf;
    delete[]pwBuf;

    pBuf = NULL;
    pwBuf = NULL;

    return retStr;
}

// GBK字符串转成json识别的UTF8字符串
std::string G2U(const std::string& gbk)
{
    int nwLen = ::MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), -1, NULL, 0);

    wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截断字符串 
    ZeroMemory(pwBuf, nwLen * 2 + 2);

    ::MultiByteToWideChar(CP_ACP, 0, gbk.c_str(), gbk.length(), pwBuf, nwLen);

    int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

    char* pBuf = new char[nLen + 1];
    ZeroMemory(pBuf, nLen + 1);

    ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

    std::string retStr(pBuf);

    delete[]pwBuf;
    delete[]pBuf;

    pwBuf = NULL;
    pBuf = NULL;

    return retStr;
}

测试示例:

int main()
{
    // read file
    std::ifstream ifs("file.json");
    json js;
    ifs >> js;
    ifs.close();


    std::string strName = js["name"];
    std::string str = utf8_to_str(strName);
    str += "+新中文测试";
    js["name"] = str_to_utf8(str);



    // write file
    std::ofstream ofs("newfile.json");
    ofs << std::setw(4) << js << std::endl;
    ofs.close();


    return 0;
}

file.json文件内容:

{
    "name": "2023年08月03日+中文测试",
    "object": {
        "key1": "test",
        "key2": 123.4
    },
    "pi": 3.141
}

newfile.json文件内容:

{
    "name": "2023年08月03日+中文测试+新中文测试",
    "object": {
        "key1": "test",
        "key2": 123.4
    },
    "pi": 3.141
}

你可能感兴趣的:(C/C++,json,c++)