Qt+JSON简单例子

news2024/10/6 14:33:20

Qt+JSON简单例子

  • Qt+JSON
  • example2
  • 参考

Qt+JSON

#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

#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

#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

{
    "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

#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

#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;
}
{
    "ID": 1,
    "date": "20190911",
    "name": "zhangsan"
}

参考

  • Cappuccino-jay【QT】Qt使用QJson生成json文件并保存
  • 其实我也恋长安 QT5中如何将数据转换为JSON格式

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1138545.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MarkDown详细入门笔记

本帖整理了MarkDown的入门学习笔记~ 一.介绍 Markdown 是一种轻量级的「标记语言」&#xff0c;它的优点很多&#xff0c;目前也被越来越多的写作爱好者&#xff0c;撰稿者广泛使用。 诸如微信公众平台、CSDN博客、还有Typora中写文档的部分&#xff0c;均涉及到MD的功能~ 它…

【rust/esp32】wsl2开发环境搭建与测试

文章目录 说在前面流程可能的问题wsl2相关rust相关vscode相关build相关 测试吐槽参考 说在前面 esp型号&#xff1a;esp32s3开发环境&#xff1a;wsl2rustc版本&#xff1a;rustc 1.73.0-nightlyesp idf版本&#xff1a;v5.1.1 流程 目前是按照这个demo的流程可以跑通修改demo…

【spark客户端】Spark SQL CLI详解:怎么执行sql文件、注释怎么写,支持的文件路径协议、交互式模式使用细节

文章目录 一. Spark SQL Command Line Options(命令行参数)二. The hiverc File1. without the -i2. .hiverc 介绍 三. 支持的路径协议四. 支持的注释类型五. Spark SQL CLI交互式命令六. Examples1. running a query from the command line2. setting Hive configuration vari…

influxdb基本使用及其源码解析

文章目录 基本介绍简介属性特点场景 相关概念seriesseries cardinalityShardShard groupShard DurationRetention policyTSMLSM 源码解析编译IDE调试服务启动metaShardShard groupRetentionPolicyDatabaseInfo Data数据写入SeriesIndexInmem Indextsi index StoreShardEngineTS…

【Javascript】函数之形参与实参

function c(a,b){return ab;}var sumc(3,4);console.log(sum);a,b为形参 3,4为实参 形参和实参是⼀⼀对应的数量可以不对应参数的类型不确定函数可以设置默认参数实参可以是字⾯量也可以是变量

规则推理桌游

目录 Eleusis Express 1&#xff0c;规则 2&#xff0c;出牌规则示例 3&#xff0c;中文规则 Eleusis Express 原文&#xff1a;Eleusis Express 1&#xff0c;规则 简单来说就是需要一个主持人想一个出牌规则&#xff0c;其他人通过出牌试探过程推理出这个出牌规则。 …

python:使用Flask-SQLAlchemy对数据库增删改查的简单示例

以下将介绍Flask-SQLAlchemy对数据库增删改查的简单示例。 一、安装所需的库 pip install flask flask-sqlalchemy flask-mysql 二、创建数据表 本示例使用mysql创建数据库和表 CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(255) DEFAULT NULL…

数据结构与算法-二叉树的遍历

&#x1f31e; “少年没有乌托邦&#xff0c;心向远方自明朗&#xff01;” 二叉树 &#x1f388;1.二叉树的遍历&#x1f52d;1.1先序遍历&#x1f52d;1.2中序遍历&#x1f52d;1.3后序遍历&#x1f52d;1.4层次遍历&#x1f52d;1.5二叉树遍历的递归算法&#x1f4dd;1.5.1先…

centos部署tomcat

Java Downloads | Oracle

mq的使用方法

mq的使用方法 1、先写好自己的业务以及只会需要mq异步调用的业务 2、在先前的业务中发送mq消息 mqProducer.syncSend(ActivityRedisConstant.TOPIC_SAVE_SIGNUP, saveSignUpMsg); 3、设定好mq的topic消息主题 Value(“${mq.signup-topic:saas-signup}”)从nacos中取如果没…

java代码审计-换行符CRLF注入

CRLF 的缩写是指回车和换行操作&#xff0c;其中 CR 为 ASCII 中的第 13 个字符&#xff0c;也 写作 \r , LF 是 ASCII 中的第 10 个字符&#xff0c;也写作 \n &#xff0c;因此 CRLF 一般翻译为回车换行注入漏洞。 什么是CRLF注入漏洞? CRLF 即【回车\r换行\n】的简…

Centos安装RabbitMQ,JavaSpring发送RabbitMQ延迟延时消息,JavaSpring消费RabbitMQ消息

1&#xff0c;版本说明 erlang 和 rabbitmq 版本说明 https://www.rabbitmq.com/which-erlang.html 确认需要安装的mq版本以及对应的erlang版本。 2&#xff0c;下载安装文件 RabbitMQ下载地址&#xff1a; https://packagecloud.io/rabbitmq/rabbitmq-server Erlang下载地…

在微信小程序云开发中引入Vant Weapp组件库

介绍 Vant 是一个轻量、可靠的移动端组件库&#xff0c;于 2017 年开源。 目前 Vant 官方提供了 Vue 2 版本、Vue 3 版本和微信小程序版本&#xff0c;并由社区团队维护 React 版本和支付宝小程序版本。 介绍 - Vant Weapp (youzan.github.io) Vant Weapp需要安装 node.js&…

nodejs+vue 电子书阅读系统

本文首先介绍了电子书阅读系统的发展背景与发展现状&#xff0c;然后遵循软件常规开发流程&#xff0c;首先针对系统选取适用的语言和开发平台&#xff0c;随着网络技术的不断发展&#xff0c;多媒体技术应用渐渐的出现在教育领域中&#xff0c;电子书阅读已经成为社会的一个热…

02-URL与资源

浏览​因特网资源 URI是一类更通用的资源标识符&#xff0c;URL与URN是它的子集URL通过描述资源的位置来标识资源HTTP规范将更通用的概念URI作为资源标识符&#xff0c;实际上&#xff0c;HTTP应用程序处理的知识URI的URL子集URL可以通过HTTP之外的其他协议来访问资源。 http链…

Unity C#中LuaTable、LuaArrayTable、LuaDictTable中数据的增删改查

LuaTable、LuaArrayTable、LuaDictTable中数据的增删改查 介绍Lua表lua表初始化lua移除引用lua中向表中添加数据lua中表中移除数据lua表中连接数据lua表中数据排序获取lua表长度获取表中最大值 UnityC#中LuaTableUnityC#中LuaArrayTable、LuaDictTable、LuaDictTable<K,V>…

HTTP发起请求与收到响应的大致过程

可以《《透视 HTTP 协议》Windows 10 搭建最小实验环境》搭建环境&#xff0c;之后才能进行下边的操作。 1.鼠标左键点击两下www目录下的start.bat批处理文件。 2.打开Wireshark&#xff0c;然后选择Adapter for loopback traffic capture。 3.然后把tcp.port 80 || udp.…

基于Springboot自习预约管理系统

功能介绍&#xff1a; 基于Springboot自习预约管理系统。该系统为后台管理系统&#xff0c;无前台。主要角色有&#xff1a;管理员和学生。 主要功能&#xff1a; 学生信息管理&#xff1a;学号、姓名、专业、班级、年级、联系方式 教室信息管理&#xff1a;教室、教室号、楼…

el-form那些事

vue3element-plus el-form那些事 输入框后拼接文字 输入框后拼接文字 <el-form-item :label"t(location.locationLength)" prop"locationLength"><el-input v-model"form.locationLength" :placeholder"t(location.inputLocation…

深度学习中语义分割、实例分割、目标检测和图像分类区别

语义分割 实例分割 目标检测 语义分割&#xff1a;需要判断每个像素属于哪一个类别&#xff0c;属于像素级别分类标注 实例分割&#xff1a;相较于语义分割 会将同一类别的不同物体进行分离标注 目标检测&#xff1a;输入图像通常包含多个物体&#xff0c;对物体的位置与类别进…