我今天碰到一个问题,就是使用的C++代码发送json数据的时候,有中文的UTF-8编码.使用 boost::property_tree::ptree发送数据的时候,我输入的是
boost::property_tree::ptree root;
root.put<std::string>("location","四川成都");
std::stringstream stream;
boost::property_tree::write_json(stream,root,false);
std::string josnString = stream.str();
其中发送的时候我发现,里面的内容不是unicode值,面是UTF-8的内存值.为了解决这个问题花了我大半天的时间,还没有解决.最后是超哥给我一段代码解决的.回过头来理解,其实是我没有真正认真的思考这个问题.相当然的写了,最终是错的.解决的办法如下:
void ChangeToUnicode (const std::string& utf8, std::vector< unsigned int >& unicode)
{
for (std::size_t i = 0, size = utf8.size(); i < size;)
{
unsigned long uni;
int bytes = 0;
bool error = false;
unsigned char ch = utf8[i++];
if (ch <= 0x7F)
{
uni = ch;
bytes = 1;
}
else if (ch <= 0xBF)
{
return ;
}
else if (ch <= 0xDF)
{
uni = ch & 0x1F;
bytes = 2;
}
else if (ch <= 0xEF)
{
uni = ch & 0x0F;
bytes = 3;
}
else if (ch <= 0xF7)
{
uni = ch & 0x07;
bytes = 4;
}
else
{
return ;
}
for (int j = 1; j < bytes; ++j)
{
if (i == size)
return ;
unsigned char ch = utf8[i++];
if (ch < 0x80 || ch > 0xBF)
return ;
uni <<= 6;
uni += ch & 0x3F;
}
if (uni >= 0xD800 && uni <= 0xDFFF)
return ;
if (uni > 0x10FFFF)
return ;
unicode.push_back(uni);
}
}
std::string Utf8ToAscii(const std::string& utf8)
{
std::vector<unsigned int> unicode;
ChangeToUnicode(utf8, unicode);
std::stringstream ss;
ss << std::hex;
for (auto code : unicode) {
ss << "\\u" << code;
}
return ss.str();
}
还有一个问题就是生成的json中,有这个"\\u",而应该是"\u"就对了.为了解决这个问题,需要自己写函数遍历字符串,替换所有出现的值.代码如下:
std::string& KDClient::replace_all_distinct(std::string& str,const std::string& old_value,const std::string& new_value)
{
for(std::string::size_type pos(0); pos!=std::string::npos; pos+=new_value.length())
{
if( (pos=str.find(old_value,pos))!=std::string::npos )
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}
replace_all_distinct(josnString,"\\\\","\\");
基本思路是这样,明天搞另一个项目.最近过的心烦,事儿真多,年纪大了,就是不开心的事就多了.