本文时间是2023年,我用的cppjson是直接从git上下载的,是包含三个文件:
json.h
json-forwards.h
jsoncpp.cpp
直接包含到程序中跟着自己的代码编译就好,然后遇到了输出的json文件需要包含中文的情况,但是只能输出类似”\u0497\u0423“这种的编码格式,然后也是在网上搜索了一下别人的解决方案。然后发现因为代码的不同,解决办法也不一样,如果你的jsoncpp.cpp代码中的valueToQuotedStringN函数是如下的,只需将参数中的:bool emitUTF8=false 改成 bool emitUTF8=true。
static String valueToQuotedStringN(const char* value, size_t length,
bool emitUTF8 = false) {
if (value == nullptr)
return "";
if (!doesAnyCharRequireEscaping(value, length))
return String("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to String is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL
String result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
for (const char* c = value; c != end; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.)
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default: {
if (emitUTF8) {
unsigned codepoint = static_cast<unsigned char>(*c);
if (codepoint < 0x20) {
appendHex(result, codepoint);
} else {
appendRaw(result, codepoint);
}
} else {
unsigned codepoint = utf8ToCodepoint(c, end); // modifies `c`
if (codepoint < 0x20) {
appendHex(result, codepoint);
} else if (codepoint < 0x80) {
appendRaw(result, codepoint);
} else if (codepoint < 0x10000) {
// Basic Multilingual Plane
appendHex(result, codepoint);
} else {
// Extended Unicode. Encode 20 bits as a surrogate pair.
codepoint -= 0x10000;
appendHex(result, 0xd800 + ((codepoint >> 10) & 0x3ff));
appendHex(result, 0xdc00 + (codepoint & 0x3ff));
}
}
} break;
}
}
result += "\"";
return result;
}
最后还是建议大家用最新的这种源码的jsoncpp代替之前需要你调用dll的,之后代码复用啥的,这种纯源码方式确实要省事很多~