You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jsoncpp导出文本时转义Unicode字符问题求助

解决Jsoncpp提取字符串写入TXT时Unicode字符转义问题

问题场景

从JSON文件提取内容写入TXT时,非ASCII Unicode字符(如中文引号“”)被转义为\u201c、\u201d格式,当前输出为"He said \u201cHey stop \u201d.",期望输出为"He said “stop!”."。

问题成因

你使用的Json::StyledStreamWriter是用于生成符合JSON规范的输出,默认会将非ASCII字符转义为\uXXXX格式,这是JSON的标准行为,和UTF-8/UTF-16编码无关。

解决方案

无需通过Jsoncpp的Writer类写入内容,直接提取原始字符串后写入文件即可,步骤如下:

  • 提取原始字符串:从Json::Value中调用asString()方法获取未转义的原始字符串
  • 直接写入文件:用C++文件流输出该字符串,同时确保文件以UTF-8编码保存避免乱码

修改后的示例代码

Json::Value root;
Json::Reader reader;
ifstream file("fileName");
// 用二进制模式打开避免换行符自动转换
std::ofstream txtFile("txtFileName", std::ios::out | std::ios::binary);

// Windows系统下设置UTF-8编码(Linux/macOS通常默认支持)
#ifdef _WIN32
    std::locale utf8_locale(std::locale(), new std::codecvt_utf8<wchar_t>);
    txtFile.imbue(utf8_locale);
#endif

reader.parse(file, root);
Json::Value events = root["events"];

// 提取未转义的原始字符串
std::string tempDialogue = events[eventIndex]["pages"][pageIndex]["list"][listIndex]["parameters"][0].asString();
// 直接写入TXT文件
txtFile << tempDialogue;

file.close();
txtFile.close();

补充说明

  • 如果字符串包含宽字符,可改用std::wofstream配合asWString()方法提取写入
  • 若必须使用Jsoncpp的Writer类,可自定义Writer配置(如调整转义规则),但直接提取字符串的方式更简便直接

内容的提问来源于stack exchange,提问作者hoboayoyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:05:19