gpt4 book ai didi

c++ - 无法使用 boost read_json 读取变音符号

转载 作者:行者123 更新时间:2023-11-30 01:38:32 27 4
gpt4 key购买 nike

我无法用 boost::property_tree::read_json 解决我的问题。我有带有 MBCS 编码(多字节字符集)的 MFC 项目。我在读取带有 ä 字符的数据时出错。这是我的例子:

namespace pt = boost::property_tree;

pt::ptree rootRequest;

//Save data in property tree
rootRequest.put("test", "Test ä");

//create stringstream
std::stringstream ss;

//Write rootRequest to stringstream
try
{
pt::write_json(ss, rootRequest);
}
catch (std::exception const &e)
{
TRACE("Error: [%s]\n", e.what());
}

//Get string from stringstream
std::string strRequest = ss.str();
TRACE("data: [%s]\n", CString(strRequest.c_str()));

//Clear stringstream
ss.str(std::string());

//Sate data to stringstream
ss << strRequest;

//Save string data in ptree value
pt::ptree rootResponse;
try
{
pt::read_json(ss, rootResponse); //Here I'm getting error

}
catch (std::exception const &e)
{
TRACE("Error: [%s]\n", e.what());
}

我收到以下异常:

<unspecified file>(2): invalid code sequence

这样读取数据的正确方法是什么?我希望有人可以帮助我。我需要将数据保存在 string 中,然后再次将其读取到 stringstream。这部分无法更改。

最佳答案

JSON 不能存储 MBCS 字符串。这意味着在保存之前必须将所有标签和值转换为 UTF-8 或 UTF-16。

UTF-8 是 JSON 的通常选择,不仅因为它使用较少的字符串内存,还因为 UTF-8 编码具有一对一的唯一字形编码,而 UTF-16 则没有。

以下是您转换字符串的方式:

MBCS 到 Unicode:

#include <windows.h>
#include <string>

std::wstring MBCS_to_UTF16(LPCSTR sz)
{
// MBCS to UNICODE
std::wstring strResult;

size_t nCharsDone = 0;
const size_t nMaxsWords = 6 * strlen(sz);

strResult.resize(nMaxsWords + 1);

if (S_OK == ::mbstowcs_s(&nCharsDone, &strResult[0], nMaxsWords + 1, sz, nMaxsWords))
strResult.resize(nCharsDone);
else
strResult.clear();
return strResult;
}

UTF16 <-> UTF8:

#include <boost/locale.hpp>

std::string strUTF8 = boost::locale::conv::utf_to_utf<char>(L"hello"); //
std::wstring strUTF16 = boost::locale::conv::utf_to_utf<wchar_t>("hello");

UTF16 到 MBCS:

std::string UTF16_to_MBCS(LPCWSTR wsz)
{
// MBCS to UNICODE
std::string strResult;

size_t nCharsDone = 0;
const size_t nMaxWords = 2 * wcslen(wsz);

strResult.resize(nMaxWords + 1);

if (S_OK == ::wcstombs_s(&nCharsDone, &strResult[0], nMaxWords + 1, wsz, nMaxWords))
strResult.resize(nCharsDone);
else
strResult.clear();
return strResult;
}

关于c++ - 无法使用 boost read_json 读取变音符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47631796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com