QJsonDocument 读取不同编码格式的 json 文件

int main()
{
    QString jsonFileName = "myJsonFile.json";
    QJsonDocument m_jsonDocument = QJsonDocument();
    QFile jsonFile(jsonFileName);

    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }

    QString m_readCodec = "GBK";
    QByteArray data;
    if ("UTF-8" == m_readCodec)
    {
        //直接读取内容放入QByteArray 对象data中 
        data = jsonFile.readAll();   
    }
    else {
        QTextStream stream(&jsonFile);
        //常用的编码方式有: UTF-8  UTF-16  GBK  UTF-16BE   UTF-16LE   UTF-32  UTF-32BE  UTF-32LE
        stream.setCodec(m_readCodec.toLatin1().constData());
        QString text = stream.readAll();
        data = text.toUtf8();
    }
    jsonFile.close();
    //解析JSON数据:使用QJsonDocument将读取的JSON数据解析为Qt可以操作的结构。
    m_jsonDocument = QJsonDocument::fromJson(data);
}

读取json文件,采用QTextStream的方式,可以通过setCodec设置读取文件的编码方式;

m_readCodec 是QString类型变量,用于存储编码方式;

Qt中支持的编码方式有:
Big5
Big5-HKSCS
CP949
EUC-JP
EUC-KR


GB18030 -->The GBK codec provides conversion to and from the Chinese GB18030/GBK/GB2312 encoding


HP-ROMAN8
IBM 850
IBM 866
IBM 874
ISO 2022-JP
ISO 8859-1 to 10
ISO 8859-13 to 16
Iscii-Bng, Dev, Gjr, Knd, Mlm, Ori, Pnj, Tlg, and Tml
KOI8-R
KOI8-U
Macintosh
Shift-JIS
TIS-620
TSCII
UTF-8
UTF-16
UTF-16BE
UTF-16LE
UTF-32
UTF-32BE
UTF-32LE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值