(Qt6 : 12-1) read/write JSON

Posted by : at

Category : Qt


#include <QCoreApplication>
#include <QDebug>
#include "test.h"
#include "converter.h"


void writeJson(QString path)
{
    Test t;
    t.fill();
    Converter::writeJson(&t, path);
}

void readJson(QString path)
{
    Test *t;
    t = Converter::readJson(path);

    if(!t)
    {
        qInfo() << "Object not loaded";
        return;
    }

    qInfo() << "Name:" << t->name();
    foreach(QString key, t->map().keys())
    {
        qInfo() << key << " : " << t->map().value(key);
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString path = "test.txt";

    writeJson(path);
    readJson(path);

    return a.exec();
}
#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
#include <QMap>
#include <QDataStream>

class Test : public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = nullptr);
    void fill();
    QString name();
    void setName(QString value);
    QMap<QString, QString> map();
    void setMap(QMap<QString, QString> newMap);

    friend QDataStream& operator <<(QDataStream &stream, const Test &t)
    {
        qInfo() << "Operator <<";
        stream << t.m_name;
        stream << t.m_map;
        return stream;
    }

    friend QDataStream& operator >>(QDataStream &stream, Test &t)
    {
        qInfo() << "Operator >>";
        stream >> t.m_name;
        stream >> t.m_map;
        return stream;
    }



signals:

private:
    QString m_name;
    QMap<QString, QString> m_map;
};

#endif // TEST_H
#include "test.h"

Test::Test(QObject *parent) : QObject(parent)
{

}

void Test::fill()
{
    m_name = "test object";
    for(int i = 0; i < 10; i++) {
        QString num = QString::number(i);
        QString key = "Key: " + num;
        QString value = "This is item number: " + num;
        m_map.insert(key,value);
    }
}

QString Test::name()
{
    return m_name;
}

void Test::setName(QString value)
{
    m_name = value;
}

QMap<QString, QString> Test::map()
{
    return  m_map;
}

void Test::setMap(QMap<QString, QString> newMap)
{
    m_map = newMap;
}
#ifndef CONVERTER_H
#define CONVERTER_H

#include <QObject>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QVariant>
#include <QVariantMap>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMap>
#include "test.h"

class Converter : public QObject
{
    Q_OBJECT
public:
    explicit Converter(QObject *parent = nullptr);

    static void writeJson(Test *obj, QString path);
    static Test* readJson(QString path);

signals:

};

#endif // CONVERTER_H
#include "converter.h"

Converter::Converter(QObject *parent) : QObject(parent)
{

}

void Converter::writeJson(Test *obj, QString path)
{
    QVariantMap map;
    QVariantMap items;
    map["name"] = obj->name();
    foreach(QString key, obj->map().keys())
    {
        items.insert(key, QVariant(obj->map().value(key)));
    }

    map["items"] = QVariant(items);

    QJsonDocument document = QJsonDocument::fromVariant(map);
    QFile file(path);
    if(!file.open(QIODevice::WriteOnly)) {
        qCritical() << "Could not write file!";
        qCritical() << file.errorString();
        return;
    }

    file.write(document.toJson());
    file.close();
}

Test *Converter::readJson(QString path)
{
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly)) {
        qCritical() << "Could not read file!";
        qCritical() << file.errorString();
        return nullptr;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonDocument document = QJsonDocument::fromJson(data);
    Test *t = new Test();
    t->setName(document["name"].toString());
    QVariantMap vmap = qvariant_cast<QVariantMap>(document["items"]);

    QMap<QString,QString> map;
    foreach(QString key, vmap.keys())
    {
        map.insert(key,vmap[key].toString());
    }
    t->setMap(map);

    return t;
}

About Taehyung Kim

안녕하세요? 8년차 현업 C++ 개발자 김태형이라고 합니다. 😁 C/C++을 사랑하며 다양한 사람과의 협업을 즐깁니다. ☕ 꾸준한 자기개발을 미덕이라 생각하며 노력중이며, 제가 얻은 지식을 홈페이지에 정리 중입니다. 좀 더 상세한 제 이력서 혹은 Private 프로젝트 접근 권한을 원하신다면 메일주세요. 😎

Star
Useful Links