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中  只有在要寫入文件比如 本人遇到的例子, 才進行轉碼

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章