qt 創建和解析中文字符 json

{
    "student": "學生事務管理系統",
    "version": 500,
    "windows": true
}

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QStringList>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>
#include <QString>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>

#include <qtextcodec.h>
#pragma execution_character_set("utf-8")
QByteArray byte_array;
QByteArray byte_array1;



void createJson()
{
   QJsonObject json;
   json.insert("version", 500);
   json.insert("windows", true);
   json.insert ("student", (QStringLiteral("學生事務管理系統")));

   QJsonDocument document;
   document.setObject(json);
   byte_array= document.toJson();
   QString json_str = QString::fromLocal8Bit(byte_array);



QFile t_file("D:/00742672/Desktop/1.json");      //生成一個文件
if(!t_file.open(QIODevice::WriteOnly))
{
  qDebug() << "打開文件失敗";
}
QTextStream t_stream(&t_file);
t_stream<<json_str;
t_file.close(); //關閉文件


}


void paserJsonObject(QString f)   //解析dev1.json
{
   QString value= ReadFile(f);
   QJsonParseError json_error;
   QJsonDocument parse_doucment = QJsonDocument::fromJson(value.toUtf8(), &json_error);
   qDebug()<<"json_error.error"<<json_error.error;
   if(json_error.error == QJsonParseError::NoError)
   {
       if(parse_doucment.isObject())
       {

           QJsonObject obj = parse_doucment.object();
           if(obj.contains("student"))
           {
            QJsonValue name_value = obj.take("student");
             if(name_value.isString())
          {
             QString name = name_value.toString();  /*.toLocal8Bit().data()*/;
             qDebug()<<"student="<<name;
          }
           }
         if(obj.contains("version"))
   {

       QJsonValue version_value = obj.take("version");
       if(version_value.isDouble())
       {
   int version = version_value.toVariant().toInt();
    qDebug()<<"version="<<version;
       }
   }
   if(obj.contains("windows"))
   {
       QJsonValue version_value = obj.take("windows");
       if(version_value.isBool())
       {
   bool flag = version_value.toBool();
   qDebug()<<"windows="<<flag;
       }
   }
       }
   }

}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    createJson();
    paserJsonObject("D:/00742672/Desktop/1.json");
    return a.exec();
}



https://blog.csdn.net/lidandan2016/article/details/86404757 解決中文亂碼


QString::fromLocal8Bit("提示")

不過在Qt5中,提供了一個專門的處理宏,來支持中文常量,那就是QStringLiteral,但它只能處理常量。
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QStringLiteral("中文顯示"));



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