在使用jsoncpp库的时候发现写入json的文件有中文乱码的问题,查阅资料后找到了解决办法。找到jsoncpp.sln解决方案。使用Visual Studio 2017开发工具打开jsoncpp.sln解决方案,找到“json_tool.h”文件的codePointToUTF8函数,修改该函数,如下:
/// Converts a unicode code-point to UTF-8.
static inline String codePointToUTF8(unsigned int cp) {
String result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f) {
result.resize(1);
result[0] = static_cast<char>(cp);
} else if (cp <= 0x7FF) {
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
// 2021-12-01 Added by M.C. Located in Wuhan. In order to Support GBK2312 Chinese.
else if ((cp >= 0x2E80 && cp <= 0xA4CF) || (cp >= 0xF900 && cp <= 0xFAFF) || (cp >= 0xFE30 && cp <= 0xFE4F) || (cp >= 0xFF00 && cp <= 0xFFEF) || (cp >= 0x2160 && cp <= 0x2169)) {
wchar_t src[2] = L"";
char dest[5] = "";
src[0] = static_cast<wchar_t>(cp);
std::string curLocale = setlocale(LC_ALL, NULL);
setlocale(LC_ALL, "chs");
wcstombs_s(NULL, dest, 5, src, 2);
result = dest;
setlocale(LC_ALL, curLocale.c_str());
}
return result;
}
找到“json_writer.cpp”文件中的valueToQuotedStringN函数,修改其中的default字段为:
default: {
result += *c;
}break;
/*
default: {
if (emitUTF8) {
result += *c;
} else {
unsigned int codepoint = utf8ToCodepoint(c, end);
const unsigned int FIRST_NON_CONTROL_CODEPOINT = 0x20;
const unsigned int LAST_NON_CONTROL_CODEPOINT = 0x7F;
const unsigned int FIRST_SURROGATE_PAIR_CODEPOINT = 0x10000;
// don't escape non-control characters
// (short escape sequence are applied above)
if (FIRST_NON_CONTROL_CODEPOINT <= codepoint &&
codepoint <= LAST_NON_CONTROL_CODEPOINT) {
result += static_cast<char>(codepoint);
} else if (codepoint <
FIRST_SURROGATE_PAIR_CODEPOINT) { // codepoint is in Basic
// Multilingual Plane
result += "\\u";
result += toHex16Bit(codepoint);
} else { // codepoint is not in Basic Multilingual Plane
// convert to surrogate pair first
codepoint -= FIRST_SURROGATE_PAIR_CODEPOINT;
result += "\\u";
result += toHex16Bit((codepoint >> 10) + 0xD800);
result += "\\u";
result += toHex16Bit((codepoint & 0x3FF) + 0xDC00);
}
}
} break;
//*/
}
}
result += "\"";
return result;
保存后重新生成编译jsoncpp_lib工程,生成相应的jsoncpp.dll和jsoncpp.lib,该库支持读写中文字符。