Qt+JSON简单例子

Qt+JSON简单例子

Qt+JSON

cpp 复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QTextCodec>
#include <QFile>
#include <QTextStream>
#include "json.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();
}

MainWindow::~MainWindow()
{
    delete ui;
}

int MainWindow::init()
{
    int arr[] = { 1, 2, 3 };
    double darr[] = { 4.2, 5.2 };
    bool barr[] = { true, false, true, false };
    QString value = "str";
    QJsonObject obj;
    obj.insert("Name", "Apple");
    obj.insert("Color", "Red");
    obj.insert("Weight", 0.2);

    JSON* json = new JSON();
    json->writeJson("bool", true);
    json->writeJson("int", 1);
    json->writeJson("double", 2.4);
    // value must be QString, implicit conversion turns string literal into bool
    json->writeJson("string", value);
    json->writeJson("str2bool", "str");
    json->writeJson("bool array", barr, 4);
    json->writeJson("int array", arr, 3);
    json->writeJson("double array", darr, 2);
    json->writeJson("object", obj);
    qDebug() << json->getJson();

    QString Passwdfile("hello.json");
    json->saveJson(Passwdfile);

    QString json_data = json->toString();
    ui->textEdit->setText(json_data);

    //原文链接:https://blog.csdn.net/Cappuccino_jay/article/details/125619033

    return 0;
}

json.h

cpp 复制代码
#ifndef JSON_H
#define JSON_H

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

class JSON {
public:
    JSON();

    QJsonObject getJson();
    QJsonObject loadJson(const QString& filepath);
    void writeJson(const QString key, bool value);
    void writeJson(const QString key, int value);
    void writeJson(const QString key, double value);
    void writeJson(const QString key, QString value);
    void writeJson(const QString key, bool* array, int length);
    void writeJson(const QString key, int* array, int length);
    void writeJson(const QString key, double* array, int length);
    void writeJson(const QString key, QJsonObject object);
    bool saveJson(const QString& filepath);
    QString toString();

private:
    QJsonObject json;
};
#endif // JSON_H

json.cpp

cpp 复制代码
#include <QDebug>
#include <QFile>
#include <QIODevice>

#include "json.h"

JSON::JSON()
{
}

QJsonObject JSON::getJson()
{
    return json;
}

QJsonObject JSON::loadJson(const QString& filepath)
{
    QFile loadFile(filepath);

    if (!loadFile.open(QIODevice::ReadOnly))
        qDebug() << "Unable to load JSON file";

    QByteArray allData = loadFile.readAll();
    loadFile.close();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));

    if (json_error.error != QJsonParseError::NoError)
        qDebug() << "JSON error!";

    QJsonObject rootObj = jsonDoc.object();
    return rootObj;
}

// NOTE: implicit conversion turns string literal into bool
void JSON::writeJson(const QString key, bool value)
{
    json.insert(key, value);
}

void JSON::writeJson(const QString key, int value)
{
    json.insert(key, value);
}

void JSON::writeJson(const QString key, double value)
{
    json.insert(key, value);
}

// value only support QString
void JSON::writeJson(const QString key, QString value)
{
    json.insert(key, QString(value));
}

void JSON::writeJson(const QString key, bool* array, int length)
{
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, int* array, int length)
{
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, double* array, int length)
{
    QJsonArray arr;
    for (int i = 0; i < length; i++)
        arr.append(array[i]);
    json.insert(key, arr);
}

void JSON::writeJson(const QString key, QJsonObject object)
{
    json.insert(key, object);
}

bool JSON::saveJson(const QString& filepath)
{
    QJsonDocument document;
    document.setObject(json);
    QFile file(filepath);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug() << "Fail to save contents to JSON file";
        return false;
    }

    file.write(document.toJson());

    return true;
}

QString JSON::toString()
{
    QJsonDocument document;
    document.setObject(json);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString str(byteArray);
    return str;
}

hello.json

bash 复制代码
{
    "bool": true,
    "bool array": [
        true,
        false,
        true,
        false
    ],
    "double": 2.4,
    "double array": [
        4.2,
        5.2
    ],
    "int": 1,
    "int array": [
        1,
        2,
        3
    ],
    "object": {
        "Color": "Red",
        "Name": "Apple",
        "Weight": 0.2
    },
    "str2bool": true,
    "string": "str"
}

example2

json.h

cpp 复制代码
#ifndef JSON_H
#define JSON_H

#include <QString>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QFile>
#include <QTextStream>
#include <QDebug>

struct Today
{
    int ID;
    QString date;
    char name[32];
};

class Json
{
public:
    Json();
public:
    int init();
    bool saveJson(const QString& filepath, QJsonObject &json);

private:
    //顺便给结构体给一个变量
    Today today;
};
#endif // JSON_H

json.cpp

cpp 复制代码
#include "json.h"

Json::Json()
{
    today.date = "20190911";
    today.ID = 001;
    int len = strlen("zhangsan");
    memcpy(today.name, "zhangsan", len);
    today.name[len] = '\0';
}

int Json::init()
{
    QJsonObject json;//构建json对象json
    json.insert("ID", today.ID);
    json.insert("date", today.date);
    json.insert("name", today.name);

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

    QString Passwdfile("hello3.json");
    saveJson(Passwdfile, json);

    //原文链接:https://blog.csdn.net/ljwoainia/article/details/100735303
    return 0;
}

bool Json::saveJson(const QString& filepath, QJsonObject &json)
{
    QJsonDocument document;
    document.setObject(json);
    QFile file(filepath);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug() << "Fail to save contents to JSON file";
        return false;
    }

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

    qDebug() << "finish to save contents to JSON file" << endl;

    return true;
}
bash 复制代码
{
    "ID": 1,
    "date": "20190911",
    "name": "zhangsan"
}

参考

相关推荐
阳光开朗_大男孩儿2 小时前
DBUS属性原理
linux·服务器·前端·数据库·qt
Alphapeople3 小时前
Qt Modbus
开发语言·qt
竹林海中敲代码3 小时前
Qt Creator 集成开发环境 常见问题
qt·qt工具常见问题
不惑_4 小时前
最佳实践 · 如何高效索引MySQL JSON字段
java·mysql·json
长沙红胖子Qt8 小时前
关于 Qt运行加载内存较大崩溃添加扩大运行内存 的解决方法
开发语言·qt·qt扩大运行内存
gopher95118 小时前
qt相关面试题
开发语言·qt·面试
三玖诶17 小时前
在 Qt 中使用 QLabel 设置 GIF 动态背景
开发语言·qt·命令模式
只对您心动19 小时前
【QT】实现TCP服务器,客户端之间的通信
linux·服务器·c语言·开发语言·c++·qt·tcp/ip
Austim小白20 小时前
QT消息对话框学习
qt·学习
天上掉下来个程小白1 天前
请求响应-05.请求-日期参数&JSON参数
spring boot·json