Skip to content

Instantly share code, notes, and snippets.

@TheCompez
Last active September 1, 2023 17:33
Show Gist options
  • Save TheCompez/88d82b42eec4ec09c5c0c64c26a1d851 to your computer and use it in GitHub Desktop.
Save TheCompez/88d82b42eec4ec09c5c0c64c26a1d851 to your computer and use it in GitHub Desktop.
How to parse JSON inside C++ and QML
{
"model": [
{
"id": 1,
"name": "Kambiz",
"family": "Asadzadeh"
},
{
"id": 2,
"name": "Hamed",
"family": "Masafi"
},
{
"id": 3,
"name": "Sorush",
"family": "Rabiei"
},
{
"id": 4,
"name": "Hadi",
"family": "Abbasi"
}
],
"result" : true
}
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "include/mydata.hpp"
using namespace Kambiz::Asadzadeh;
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterType<JSON::MyData>("com.dotwaves.api", 1, 0, "JsonData");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
import QtQuick 2.15
import QtQuick.Window 2.15
import com.dotwaves.api 1.0
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello JSON World!")
JsonData {
id: jsonData;
}
Component.onCompleted: {
jsonData.parse(":/data.json");
if(jsonData.result) {
for(var i = 0; i < jsonData.length; i++) {
var obj = jsonData.data[i];
console.log("ID : " + obj.id)
console.log("Name : " + obj.name)
console.log("Family : " + obj.family)
}
} else {
console.warn("Any data has not found by enable status!")
}
}
}
#include "include/mydata.hpp"
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QVariantList>
// Using Namespace JSON here :)
using namespace Kambiz::Asadzadeh::JSON;
MyData::MyData()
{
//toDo...
}
bool MyData::fileExists(QString path) {
QFileInfo check_file(path);
// check if file exists and if yes, Is it really a file!
if (check_file.exists() && check_file.isFile()) {
return true;
} else {
return false;
}
}
QVariantList MyData::data() const
{
return m_data;
}
void MyData::setData(const QVariantList& data)
{
if (m_data == data)
return;
m_data = data;
emit dataChanged(m_data);
}
int MyData::length() const
{
return m_length;
}
void MyData::setLength(int length)
{
if (m_length == length)
return;
m_length = length;
emit lengthChanged(m_length);
}
bool MyData::result() const
{
return m_result;
}
void MyData::setResult(bool result)
{
if (m_result == result)
return;
m_result = result;
emit resultChanged(m_result);
}
void MyData::parse(QString path) {
QString rawData;
QVariantMap modelData;
QVariantList finalJson;
QFile file;
QDir dir(".");
if(fileExists(path)) {
{
file.setFileName(path);
file.open(QIODevice::ReadOnly | QIODevice::Text);
//Load data from json file!
rawData = file.readAll();
file.close();
// Create json document.
// Parses json as a UTF-8 encoded JSON document, and creates a QJsonDocument from it.
QJsonDocument document = { QJsonDocument::fromJson(rawData.toUtf8()) };
//Create data as Json object
QJsonObject jsonObject = document.object();
// Sets number of items in the list as integer.
setLength(jsonObject["model"].toArray().count());
foreach (const QJsonValue &value, jsonObject["model"].toArray()) {
// Sets value from model as Json object
QJsonObject modelObject = value.toObject();
modelData.insert("id", modelObject["id"].toInt());
modelData.insert("name", modelObject["name"].toString());
modelData.insert("family", modelObject["family"].toString());
// Set model data
finalJson.append(modelData);
}
// Sets data
setData(finalJson);
// Sets result by status object of model.
setResult(jsonObject["result"].toBool());
}
} else {
qWarning() << "There is no any file in this path!";
}
}
#ifndef MYDATA_HPP
#define MYDATA_HPP
#include <QObject>
#include <QVariantList>
// Beginning of JSON Namespace
namespace Kambiz::Asadzadeh::JSON {
class MyData;
/*!
* \brief The MyData class
*/
class MyData : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariantList data READ data WRITE setData NOTIFY dataChanged)
Q_PROPERTY(bool result READ result WRITE setResult NOTIFY resultChanged)
Q_PROPERTY(int length READ length WRITE setLength NOTIFY lengthChanged)
public:
MyData();
/*!
* \brief data function returns a list of items.
* \return type as QVarianList.
*/
QVariantList data () const;
/*!
* \brief result function returns final result by status value!
* \return type as boolian.
*/
bool result () const;
/*!
* \brief : length function returns total item count!
* \return type as int
*/
int length () const;
/*!
* \brief : fileExists function checks file path!
* \param : path is string of current file path.
* \return type as boolian.
*/
bool fileExists(QString path);
/*!
* \brief : parse function gets json file from user to convert.
* \param : path is string of current file path.
*/
Q_INVOKABLE void parse(QString path);
//SLOTS
public slots:
void setData(const QVariantList& data);
void setResult(bool result);
void setLength(int length);
//SIGNALS
signals:
void dataChanged(const QVariantList& data);
void resultChanged(bool result);
void lengthChanged(int length);
private:
QVariantList m_data;
bool m_result = {false};
int m_length = {0};
};
}
// Ending of JSON Namespace
#endif // MYDATA_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment