有时候http服务器返回的json字符串的汉字是Unicode编码,直接QDebug打印是"content":"\u65b0\u6d4b\u8bd5cdn\u4e0b\u8f7d2"这种字符,不方便查看,需要转码
可以用下面的函数转换一下:
//unicode转utf-8
QString unicode2utf8(QString unicode)
{
QString result;
int index = unicode.indexOf("\\u"); //设置解码的起始位置
while (index != -1 && index < unicode.length())
{
QString flag = unicode.mid(index,2); //用于检测下一个字符是否为unicode
if(flag == "\\u") //对每一个unicode编码进行处理
{
QString s1 = unicode.mid(index + 2, 4);
result.append(s1.toUShort(0, 16));
index += 6; //每个unicode编码的字符形式都为\u****的形式,为防止出现错误与重复,在检测完毕后建议将指针后移6位
}
else if(flag == "\"}") //设置解码的终止位置
{
break;
}
else
{
//剩下一种情况为非unicode的状态的字符,一般为符号、字母和数字
QString s2 = unicode.mid(index,1);
result.append(s2);
index += 1; //为防止出现遗漏,在每个非unicode的状态的字符检测后,将指针只移动一位
}
}
return result.toUtf8().constData();
}