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

使用Boost::json_parser转换Shift-JIS编码JSON到XML时日文乱码问题解决

解决Shift-JIS编码JSON转XML乱码问题

核心原因

Boost.PropertyTree的JSON解析器默认仅支持UTF-8编码,而你的JSON采用Shift-JIS编码,直接解析会导致日文等非ASCII字符被错误识别,最终转XML时出现乱码。

具体解决方案

1. 先将Shift-JIS编码的JSON字符串转成UTF-8

在MFC环境下,可通过Windows API完成编码转换:

// 输入:Shift-JIS编码的CString
CString strShiftJISJson = _T("你的Shift-JIS格式JSON字符串");
int nLen = MultiByteToWideChar(932, 0, strShiftJISJson, -1, NULL, 0);
wchar_t* pWideBuf = new wchar_t[nLen];
MultiByteToWideChar(932, 0, strShiftJISJson, -1, pWideBuf, nLen);

// 转换为UTF-8编码
nLen = WideCharToMultiByte(CP_UTF8, 0, pWideBuf, -1, NULL, 0, NULL, NULL);
char* pUtf8Buf = new char[nLen];
WideCharToMultiByte(CP_UTF8, 0, pWideBuf, -1, pUtf8Buf, nLen, NULL, NULL);

CString strUtf8Json(pUtf8Buf);
delete[] pWideBuf;
delete[] pUtf8Buf;

注:代码中的932是Shift-JIS对应的Windows代码页编号

2. 用Boost解析UTF-8格式的JSON到PropertyTree

确保Boost读取的是UTF-8编码的字符串,避免编码错误:

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>

using namespace boost::property_tree;

ptree pt;
std::stringstream ss(strUtf8Json.GetBuffer());
read_json(ss, pt);
strUtf8Json.ReleaseBuffer();

3. 输出XML时指定UTF-8编码

Boost的XML输出默认可能使用系统编码,需显式指定UTF-8,避免二次编码问题:

std::stringstream xmlSs;
xml_writer_settings<std::string> settings('\t', 1);
settings.encoding = "UTF-8"; // 强制XML采用UTF-8编码
write_xml(xmlSs, pt, settings);

// 将UTF-8格式的XML转为MFC可用的CString(按需使用)
int xmlLen = MultiByteToWideChar(CP_UTF8, 0, xmlSs.str().c_str(), -1, NULL, 0);
wchar_t* pXmlWide = new wchar_t[xmlLen];
MultiByteToWideChar(CP_UTF8, 0, xmlSs.str().c_str(), -1, pXmlWide, xmlLen);
CString strFinalXml(pXmlWide);
delete[] pXmlWide;

额外注意事项

  • 若JSON从网络流直接读取,需按原始Shift-JIS字节流处理,不要提前做错误的编码转换。
  • 若使用Boost 1.70+版本,可尝试直接用read_json的宽字符流重载版本,但需保证输入的宽字符为正确的UTF-16/UTF-32编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:35:18