其他分享
首页 > 其他分享> > jsoncpp写文件中文乱码问题解决

jsoncpp写文件中文乱码问题解决

作者:互联网

不进行streamWritebuilder的设置,写入的中文会变成unicode形式,如下图

并且转中文不是之前写入的内容,

这里使用的是新版的jsonWrite

#include<iostream>
#include<string>
#include<json/json.h>
#include<fstream>
void StreamWrite()
{
	Json::Value root;
	root["Name"] = "王";
	root["Age"] = 20;

	//关键在于对builder的属性设置
	Json::StreamWriterBuilder builder;
	static Json::Value def = []() {
		Json::Value def;
		Json::StreamWriterBuilder::setDefaults(&def);
		def["emitUTF8"] = true;
		return def;
	}();

	builder.settings_ = def;//Config emitUTF8
	const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

	std::fstream fs;
	fs.open("save.json", std::ios::out);
	writer->write(root, &std::cout);
	writer->write(root, &fs);

}

int main()
{
	StreamWrite();
	return 0;
}

 

趟坑经历:

我把本地字节ANSI转成UNICODE(UTF-16) 然后再转成UTF-8,进行jsoncpp的写入,得到的结果是UNICODE的\uxxxx表达。

#include <codecvt>
#include<windows.h>
std::wstring ANSI2WChar(const std::string& strData)
{
    //把GB2312编码的中文字串转换为UTF-8编码的中文字串  
    int iLen = strData.length();
    CHAR* pMb = new CHAR[iLen + 1];
    int iMbLen = iLen + 1;
    ZeroMemory(pMb, iMbLen);
    memcpy_s(pMb, iMbLen, strData.c_str(), strData.length());
    //将多字节字符串编码转换成宽字符串  
    iLen = ::MultiByteToWideChar(CP_ACP, 0, pMb, iMbLen, NULL, 0);
    WCHAR* lpszW = NULL;
    lpszW = new WCHAR[iLen];
    ::wmemset(lpszW, 0, iLen);
    int iRtn = ::MultiByteToWideChar(CP_ACP, 0, pMb, iMbLen, lpszW, iLen);
    std::wstring wstr(L"");
    if (iRtn == iLen)
    {
        wstr = lpszW;
    }

    delete[] lpszW;
    delete[] pMb;
    lpszW = nullptr;
    pMb = nullptr;

    return wstr;
}
int main() {
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
    std::string utf8_string = convert.to_bytes(L"中文");

    //jsonwrite部分
}

 

标签:std,中文,iLen,jsoncpp,乱码,pMb,lpszW,include,def
来源: https://blog.csdn.net/Bang666/article/details/116755899