天天看点

qt 写json文件解决中文乱码(一)

转 参考:https://blog.csdn.net/ikisstherain/article/details/60879427

qt fromLocal8Bit()函数可以设置编码。

QT默认的编码是unicode,不能显示中文的

windows默认使用(GBK/GB2312/GB18030)

使用fromLocal8Bit()函数,实现了从本地字符集GB到Unicode的转换,用于处理汉语显示乱码等问题

static inline QString fromLocal8Bit(const QByteArray &str);该函数返回的是String类型的数

1. 字符串变量 QString toUtf8 函数

QByteArray QString::toUtf8() const   返回字节流

Returns a UTF-8 representation of the string as a QByteArray.

UTF-8 is a Unicode codec and can represent all characters in a Unicode string like QString.

2. fromLocal8Bit 函数

  QString QString::fromLocal8Bit(const QByteArray &str)        

Returns a QString initialized with the 8-bit string str.

处理步骤:

   1.   转为字节流   调用toUtf8

   2.    从GBK转为unicode    调用fromLocal8Bit

Qstring str;

QJsonObject root;

root.insert("name",QString::fromLocal8Bit((str).toUtf8()));

.....

生成文件

{"name":"工程"}  在windows下  字符编码格式为 : utf-8 无BOM

上述的逆序转换 

fromUtf8(prjName.toLocal8Bit()  toLocal8Bit 转为系统 bytearray
           

特别提醒:在qt中  只有在要写入文件比如 本人遇到的例子, 才进行转码