QT QML JSON文件的解析和修改

C++ 编写一个JSON类,完成对JSON文件数据的读写。注册为QML类型。

(1) JSON类头文件

#ifndef DJSON_H
#define DJSON_H
#include 
#include 
#include 
#include 
#include 
class DJson : public QObject
{
    Q_OBJECT
public:
    DJson();
    Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged)
    Q_INVOKABLE bool writeJsonFile(const QJsonObject &object);
    Q_INVOKABLE QJsonObject readJsonFile();
    QString source() {return m_source;}
    void setSource(const QString &path)
    {
        if(m_source != path)
        {
            m_source  = path;
            emit sourceChanged(path);
        }
    }
    static void clearJsonObject(QJsonObject &object);
signals:    
   void sourceChanged(const QString &path);
private:    
    QString m_source;
};
 
#endif // DJSON_H
(2) JSON类CPP文件
#include "djson.h"
#include 
#include 
#include 
DJson::DJson(){
}

bool DJson::writeJsonFile(const QJsonObject &object)
{    
QFile file(m_source);    
bool ok = file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate);    
if(ok == false) //不存在    
{        
     qDebug() << QString("fail to open the file: %1, %2, %3").arg(__FILE__).arg(__LINE__).arg(__FUNCTION__);                return false;    
 }   
     QJsonDocument jsonDocument;    
    jsonDocument.setObject(object);    
    QByteArray byteArray = jsonDocument.toJson(QJsonDocument::Indented);    
    QTextStream out(&file);    
    out.setCodec("UTF-8"); //yyk    
    out << byteArray;    
    if(file.isOpen())       
    file.close();       
    return true;
}
 
QJsonObject DJson::readJsonFile()
{    
   QFile file(m_source);    
   if(!file.open(QIODevice::ReadOnly | QIODevice::Text))    
    {        
      qDebug() << "Open json file failed!";        
       return QJsonObject();    
    }    
   QByteArray allData = file.readAll();    
    if(allData.isEmpty())   
       return QJsonObject();    
   QJsonParseError json_error;    
   QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));    
   if(json_error.error != QJsonParseError::NoError)    
   {       
      qDebug() <<"DJson::readJsonFile()"<< "json error!";       
       return QJsonObject();   
   }    
   QJsonObject rootObj = jsonDoc.object();    
  if(file.isOpen())       
    file.close();    
  return rootObj;
}
 
void DJson::clearJsonObject(QJsonObject &object)
{    
  QStringList strList = object.keys();    
   for(int i = 0; i < strList.size(); ++i)  
    {       
      object.remove(strList.at(i));    
    }
}
(3) main.cpp  注册为QML类型
#include 
#include 
#include "fileio/fileio.h"
#include 
int main(int argc, char *argv[])
{   
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);    
    QGuiApplication app(argc, argv);    
    qmlRegisterType("DJson", 1, 0, "DJson");    
    QQmlApplicationEngine engine;    
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));    
   if (engine.rootObjects().isEmpty())      
     return -1;    
   QObject *root = engine.rootObjects()[0];    
  if(root)    
   root->setProperty("applicationDirPath", QCoreApplication::applicationDirPath());    
   return app.exec();
}
(4) JSON类的使用。
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4
import DJson 1.0
import QtQuick.XmlListModel 2.0
Window {
    property string applicationDirPath
    property var classifyTable
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    DJson{
        id: classifyTableJsonFile
        source: applicationDirPath + "/test.json"
    }
    Row{
        spacing : 10
        Button{
            id:btn1
            text: "open"
            onClicked: {
                //console.log(applicationDirPath);
                classifyTable = classifyTableJsonFile.readJsonFile()
                console.log(JSON.stringify(classifyTable))
                dataedit.text = classifyTable["data"]
                statusedit.text = classifyTable["status"]
            }
        }
        Text {
            id: datalabel
            //anchors.topMargin: 50
            text: qsTr("data:")
            topPadding: 25
        }
        TextEdit {
            id: dataedit
            width: 80
            height: 20
            text: qsTr("0")
            font.pixelSize: 12
            topPadding: 25
        }
        Text {
            id:statuslabel
            text: qsTr("status:")
            topPadding: 25
        }
        TextEdit {
            id: statusedit
            width: 80
            height: 20
            text: qsTr("0")
            font.pixelSize: 12
            topPadding: 25
        }
        Button{
            id:btn2
            text: "save"
            onClicked: {
                classifyTable = classifyTableJsonFile.readJsonFile()
                classifyTable["data"]   =dataedit.text                
                classifyTable["status"] =statusedit.text
                classifyTableJsonFile.writeJsonFile(classifyTable)
            }
        }
        Button{
            text: "clear"
            onClicked:
            {
                dataedit.text = 0
                statusedit.text = 0
            }
        }
    }
}

你可能感兴趣的:(QT)