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

如何将std::string转换为UTF-8 解决rapidjson赋值失效问题

RapidJSON存储std::stringstream内容失效问题解决方案

核心失效原因:RapidJSON的SetString()接口默认要求传入合法UTF-8编码字符串,你当前std::stringstream内存储的是非UTF-8编码内容,同时原生调用方式不符合RapidJSON的参数要求,才会赋值失败。

具体解决步骤

  • 第一步:将非UTF-8编码的字符串转换为UTF-8编码
    若你使用Windows平台,stream内默认是GBK编码,可参考如下转换逻辑,如果你的编译环境是C++17及以上,可替换为平台专属编码转换API或第三方编码转换库(如iconv)避免弃用警告:
    #include <codecvt>
    #include <locale>
    #include <string>
    #include <windows.h>
    
    // GBK转UTF-8实现
    std::string gbk_to_utf8(const std::string& gbk_str) {
        static std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
        int wchar_len = MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, NULL, 0);
        wchar_t* tmp_wstr = new wchar_t[wchar_len];
        MultiByteToWideChar(CP_ACP, 0, gbk_str.c_str(), -1, tmp_wstr, wchar_len);
        std::string utf8_str = conv.to_bytes(tmp_wstr);
        delete[] tmp_wstr;
        return utf8_str;
    }
    
    若stream内是其他编码,替换对应转换逻辑即可。
  • 第二步:修正SetString调用写法
    RapidJSON的SetString要求显式传入字符串长度,同时关联JSON文档的内存分配器避免内存非法访问,修正后的代码如下:
    std::string raw_content = tmp_stream.str();
    std::string utf8_content = gbk_to_utf8(raw_content);
    d["key"].SetString(utf8_content.c_str(), utf8_content.size(), d.GetAllocator());
    
  • 特殊情况处理:如果你确认stream内的内容本身就是UTF-8编码,不需要额外转码,直接补全参数即可赋值成功:
    std::string raw_content = tmp_stream.str();
    d["key"].SetString(raw_content.c_str(), raw_content.size(), d.GetAllocator());
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:03