jsoncpp打包json格式toStyledString输出中文乱码解决方案

文章详细描述了对json_writer.cpp文件中valueToQuotedStringN函数的修改,主要是处理字符串时避免中文乱码的情况。通过对default分支的修改,注释掉原有代码并添加`result+=*c;`,确保了中文字符能正确保存而不会出现乱码。
摘要由CSDN通过智能技术生成

1.修改json_writer.cpp中valueToQuotedStringN函数

具体修改如下:

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));
      //  }
      //}
        result += *c;
    break;
    }
  }
  result += "\"";
  return result;
}

主要修改为default部分,注释掉原来的代码块,新加 result += *c;,改了之后保存,中文就不会乱码了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值