当前位置: 代码迷 >> 综合 >> Qt读取本地编码为ANSI的json文件,并转为QJsonDocument
  详细解决方案

Qt读取本地编码为ANSI的json文件,并转为QJsonDocument

热度:0   发布时间:2024-02-20 04:55:18.0

Qt 中提供了处理JSON数据类型的类,而处理JSON数据的基础就是将数据转换为可供Qt处理的数据类型,当我们读取的.json文件编码格式为ANSI时,使用

QJsonDocument::fromJson(const QByteArray &json, QJsonParseError *error = nullptr)进行转换时,就会出现转换失败的情况,因为QJsonDocument::fromJson()转换的二进制码流数据需要采用UTF-8编码,而Qt获取的JSON的编码格式不是UTF-8时,就会出现转换失败。下面介绍两种字符转换方法:

一、使用QTextCodec进行编码转换:

QByteArray js = file.readAll();       
QTextCodec* codec = QTextCodec::codecForName("GBK");
QString jsStr = codec->toUnicode(js);
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsStr.toUtf8());
qDebug()<<jsonDocument;

二、使用QString::fromLocal8Bit()进行转换:

QByteArray js = file.readAll();       
QString jsStr = QString::fromLocal8Bit(js);
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsStr.toUtf8());
qDebug()<<jsonDocument;