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

编程入门 行业动态 更新时间:2024-10-26 03:26:39

nlohmann::json 中文<a href=https://www.elefans.com/category/jswz/34/1768993.html style=乱码解决方案"/>

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 filestd::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 filestd::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
}

更多推荐

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

本文发布于:2024-03-08 07:04:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1720146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乱码   中文   解决方案   nlohmann   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!