包含内容:
- JSON 文件的存储&读取
- 为此配置文件提供单例模式
- 使用 hash 容器作为转化
一、QT 中的 JSON 常用类
<QJsonDocument>:
1. 作用: 用于读写 JSON 文档。
2. 函数:
- QJsonDocument::fromJson() 从文本转化为 QJsonDocument
- QJsonDocument::toJson() 从 QJsonDocument 转化为文本
- !isNull() 判断已解析文档的有效性
- isArray() 判断 JSON 文档是否包含一个数组
- isObject() 判断 JSON 文档是否包含一个对象
- array() 查询文档中的数组,可进行读取或修改
- object() 查询文档中的对象,可进行读取或修改
<QJsonArray>:
1. 作用: 表示 JSON 数组
2. 函数:
- append() 向数组中插入 QJsonValue
- size() 查询数组元素个数
- insert() 在指定索引处插入值
- removeAt() 删除指定索引的值
3. 转化:
- 一个 QJsonArray 可以和一个 QVariantList 相互转换
<QJsonObject>:
1. 作用:表示 JSON 对象,即 “key/value 对”列表,key 是独一无二的字符串,value 类型是 QJsonValue
2. 函数:
- size() 查询 “key/value 对” 的数量
- insert() 插入 “key/value 对”
- remove() 删除指定的 key
3. 转化:
- 一个 QJsonObject 可以和一个 QVariantMap 相互转换
<QJsonValue>:
1. 作用:表示 JSON 中的值
2. 函数:
- isUndefined() 查询未定义的值
- type() 查询类型
- isBool() 查询类型
- isString() 查询类型
- toBool() 转化成 bool 类型
- toString() 转化成 string 类型
- toDouble() 转化成 double 类型
3. 6种基本数据类型:
- bool (QJsonValue::Bool)
- double(QJsonValue::Double)
- string (QJsonValue::String)
- array (QJsonValue::Array)
- object (QJsonValue::Object)
- null (QJsonValue::Null)
<QJsonParseError>:
1. 作用:报告 JSON 解析中的错误
2. 常用:
- QJsonParseError::NoError 未发生错误
二、 1个 JSON 对象
1. json 对象存储格式:
{
"bool value": true,
"int value": 111,
"str value": "name"
}
2. 创建 json 对象:
// 创建 JSON 对象
QJsonObject json;
json.insert("bool value", true);
json.insert("int value", 111);
json.insert("str value", "name");
// 创建 JSON 文档
QJsonDocument doc(object);
QByteArray byteArray = doc.toJson();
// 写入文件
QString strFile = "./test.json";
QFile loadFile(strFile);
if (loadFile.open(QIODevice::WriteOnly))
{
loadFile.write(byteArray);
}
loadFile.close();
3. 读取 json 对象:
//打开文件,读取 json
QString file = "./test.json";
QFile loadFile(file);
if (loadFile.open(QIODevice::ReadOnly))
{
QByteArray allData = loadFile.readAll();
}
loadFile.close();
//将读出的json 进行转化
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(allData , &jsonError); // 转化为 JSON 文档
if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)){//解析未发生错误
if (doucment.isObject()){ // JSON 文档为对象
QJsonObject object = doucment.object(); // 转化为对象
if (object.contains("str value")){ // 包含指定的 key
QJsonValue value = object.value("str value"); // 获取指定 key 对应的 value
if (value.isString()){ // 判断 value 是否为字符串
QString strValue = value.toString(); // 将 value 转化为字符串
qDebug() << "str value: " << strValue;
}
}
if (object.contains("int value")){
QJsonValue value = object.value("int value");
if (value.isDouble()){
int intValue = value.toVariant().toInt();
qDebug() << "int value : " << intValue;
}
}
if (object.contains("bool value")){
QJsonValue value = object.value("bool value");
if (value.isBool()){
bool boolValue = value.toBool();
qDebug() << "bool value: " << boolValue ;
}
}
}
}
三、 1个 JSON 数组
1. json 数组存储格式:
[
"name",
12.5,
true
]
2. 创建 json 数组:
// 创建 JSON 数组
QJsonArray json;
json.append("name");
json.append(12.5);
json.append(true);
// 创建 JSON 文档
QJsonDocument doc(json);
QByteArray byteArray = doc.toJson();
// 写入文件
QString strFile = "./test.json";
QFile loadFile(strFile);
if (loadFile.open(QIODevice::WriteOnly))
{
loadFile.write(byteArray);
}
loadFile.close();
3. 读取 json 数组:
//打开文件,读取 json
QString file = "./test.json";
QFile loadFile(file);
if (loadFile.open(QIODevice::ReadOnly))
{
QByteArray allData = loadFile.readAll();
}
loadFile.close();
//将读出的json 进行转化
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(allData , &jsonError); // 转化为 JSON 文档
if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)){//解析未发生错误
if (doucment.isArray()){ // JSON 文档为数组
QJsonArray array = doucment.array(); // 转化为数组
int nSize = array.size(); // 获取数组大小
for (int i = 0; i < nSize; ++i){ // 遍历数组
QJsonValue value = array.at(i);
if (value.type() == QJsonValue::String){
QString strValue = value.toString();
qDebug() << strValue;
}
if (value.type() == QJsonValue::Double){
double dValue = value.toDouble();
qDebug() << dValue;
}
if (value.type() == QJsonValue::Bool){
bool bValue = value.toBool();
qDebug() << bValue;
}
}
}
}
四、多对象多数组
1. json 存储格式:
{
"str1": "aaa",
"int1": 111,
"str2": "bbb",
"struct":{
"str3": "ccc",
"str4": "ddd",
"str5": "eee"
},
"vector":[
1.5,
2.5,
3.5
]
}
2. 创建 json :
// 创建 Json 数组 - vector
QJsonArray vectorArray;
vectorArray.append(1.5);
vectorArray.append(2.5);
vectorArray.append(3.5);
// 创建 Json 对象 - struct
QJsonObject structObject;
structObject.insert("str3", "ccc");
structObject.insert("str4", "ddd");
structObject.insert("str5", "eee");
// 创建 Json 对象
QJsonObject json;
json.insert("str1", "aaa");
json.insert("str2", "bbb");
json.insert("int1", 111);
json.insert("vector", QJsonValue(vectorArray));
json.insert("struct", QJsonValue(structObject));
// 创建 Json 文档
QJsonDocument document;
document.setObject(json);
QByteArray byteArray = document.toJson(QJsonDocument::Compact);
// 写入文件
QString strFile = "./test.json";
QFile loadFile(strFile);
if (loadFile.open(QIODevice::WriteOnly))
{
loadFile.write(byteArray);
}
loadFile.close();
3. 读取 json :
//打开文件,读取 json
QString file = "./test.json";
QFile loadFile(file);
if (loadFile.open(QIODevice::ReadOnly))
{
QByteArray allData = loadFile.readAll();
}
loadFile.close();
//将读出的json 进行转化
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(allData, &jsonError); // 转化为 JSON 文档
if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)){//解析未发生错误
if (doucment.isObject()){ // JSON 文档为对象
QJsonObject object = doucment.object(); // 转化为对象
if (object.contains("str1")) {
QJsonValue value = object.value("str1");
if (value.isString()) {
QString str1 = value.toString();
qDebug() << "str1: " << str1;
}
}
if (object.contains("str2")) {
QJsonValue value = object.value("str2");
if (value.isString()) {
QString str2 = value.toString();
qDebug() << "str2: " << str2;
}
}
if (object.contains("int1")) {
QJsonValue value = object.value("int1");
if (value.isDouble()) {
int nint1 = value.toVariant().toInt();
qDebug() << "int1 : " << nint1;
}
}
if (object.contains("vector")) {
QJsonValue value = object.value("vector");
if (value.isArray()){ // Version 的 value 是数组
QJsonArray array = value.toArray();
int nSize = array.size();
for (int i = 0; i < nSize; ++i) {
QJsonValue value = array.at(i);
if (value.isDouble()) {
double dvector = value.toDouble();
qDebug() << "vector: " << dvector;
}
}
}
}
if (object.contains("struct")) {
QJsonValue value = object.value("struct");
if (value.isObject()){ // Page 的 value 是对象
QJsonObject obj = value.toObject();
if (obj.contains("str3")) {
QJsonValue value = obj.value("str3");
if (value.isString()) {
QString str3 = value.toString();
qDebug() << "str3: " << str3;
}
}
if (obj.contains("str4")) {
QJsonValue value = obj.value("str4");
if (value.isString()) {
QString str4 = value.toString();
qDebug() << "str4: " << str4;
}
}
if (obj.contains("str5")) {
QJsonValue value = obj.value("str5");
if (value.isString()) {
QString str5 = value.toString();
qDebug() << "str5: " << str5;
}
}
}
}
}
}
五、完整示例一 (一个json对象)
1. json 文件格式
{
"1":"确定",
"2":"取消"
}2. 保存容器
QHash<QString, QString>3. 提供单例模式
CJsonIO.h
#ifndef CJSONIO_H
#define CJSONIO_H
#include <QHash>
class CJsonIO
{
public:
static CJsonIO* GetInstance();
bool ReadJson(const QString& dir, const QString& fileName);
bool WriteJson(const QString& dir, const QString& fileName);
void PrintCurJson();
QString GetValue(QString key);
private:
CJsonIO();
~CJsonIO();
void Init();
private:
static CJsonIO m_jsonIO;
QHash<QString, QString> m_hash; //存储当前json
QHash<QString, QString> m_defaultHash; //存储默认json
};
#endif // CJSONIO_H
CJsonIO.cpp
#include "CJsonIO.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include <QDir>
#include <QDebug>
CJsonIO CJsonIO::m_jsonIO;
CJsonIO::CJsonIO()
:m_hash()
,m_defaultHash()
{
this->Init();
}
CJsonIO::~CJsonIO()
{
}
CJsonIO *CJsonIO::GetInstance()
{
return &m_jsonIO;
}
bool CJsonIO::ReadJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
QString file = dir + fileName;
QFile loadFile(file);
if (!loadFile.open(QIODevice::ReadOnly))
{
qDebug() << "could't open projects json";
break;
}
QByteArray allData = loadFile.readAll();
loadFile.close();
QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(allData, &jsonError); //函数说明:解析UTF-8编码的JSON文档并从中创建QJsonDocument。
QStringList keys = document.object().keys();
QHash<QString, QString> indexHash;
if (document.isNull() || (jsonError.error != QJsonParseError::NoError))
{
qDebug() << "document error";
break;
}
if (jsonError.error == QJsonParseError::IllegalUTF8String) //输入中出现非法UTF8序列
{
qDebug() << "An illegal UTF8 sequence occurred in the input";
break;
}
if (!document.isObject())
{
qDebug() << "document is not object";
break;
}
QJsonObject object = document.object();
int keySize = keys.size();
for (int i = 0; i < keySize; ++i)
{
QString strKey = keys.at(i);
if (object.contains(strKey))
{
QJsonValue value = object.value(strKey);
if (value.isString())
{
QString strValue = value.toString();
indexHash.insert(strKey, strValue);
}
}
}
this->m_hash = indexHash;
result = true;
}while(false);
return result;
}
bool CJsonIO::WriteJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
//set QJsonObject
QJsonObject object;
QHash<QString, QString>::iterator iter;
for (iter = m_hash.begin(); iter != m_hash.end(); ++iter)
{
object.insert(iter.key(), iter.value());
}
//set QJsonDocument
QJsonDocument doc(object);
QByteArray byteArray = doc.toJson();
//write document
QString strFile = dir + fileName;
QFile loadFile(strFile);
if (!loadFile.open(QIODevice::WriteOnly))
{
qDebug() << "could't open projects json";
break;
}
loadFile.write(byteArray);
loadFile.close();
result = true;
}while(false);
return result;
}
void CJsonIO::PrintCurJson()
{
QHash<QString,QString>::const_iterator iter = this->m_hash.constBegin();
while (iter != this->m_hash.constEnd())
{
QString key = iter.key();
QString value = iter.value();
qDebug() << "key:" << key << ": " << "value: " << value;
++iter;
}
}
QString CJsonIO::GetValue(QString key)
{
QString value;
QHash<QString, QString>::const_iterator iter = this->m_hash.constBegin();
while (iter != this->m_hash.constEnd())
{
QString hashKey = iter.key();
if (hashKey == key)
{
value = iter.value();
}
++iter;
}
return value;
}
void CJsonIO::Init()
{
this->ReadJson("./", "read.json");
this->m_defaultHash = this->m_hash;
}
main
#include <QCoreApplication>
#include "CJsonIO.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//json1
CJsonIO *json1 = CJsonIO::GetInstance();
QString dir = "./";
QString readName = "read.json";
QString writeFile = "write.json";
json1->ReadJson(dir, readName);
json1->WriteJson(dir, writeFile);
json1->PrintCurJson();
qDebug() << json1->GetValue("1");
return a.exec();
}
六、完整示例二 (一个 json 数组)
1. json 文件格式
[
1.2 ,
2.5 ,
3.5
]2. 保存容器
QVector<double>3. 提供单例模式
CJsonIO2.h
#ifndef CJSONIO2_H
#define CJSONIO2_H
#include <QVector>
class CJsonIO2
{
public:
static CJsonIO2* GetInstance();
bool ReadJson(const QString& dir, const QString& fileName);
bool WriteJson(const QString& dir, const QString& fileName);
void PrintCurJson();
private:
CJsonIO2();
~CJsonIO2();
void Init();
private:
static CJsonIO2 m_jsonIO;
QVector<double> m_vector;
};
#endif // CJSONIO2_H
CJsonIO2.cpp
#include "CJsonIO2.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include <QDebug>
CJsonIO2 CJsonIO2::m_jsonIO;
CJsonIO2::CJsonIO2()
:m_vector()
{
this->Init();
}
CJsonIO2::~CJsonIO2()
{
}
CJsonIO2 *CJsonIO2::GetInstance()
{
return &m_jsonIO;
}
bool CJsonIO2::ReadJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
//read document
QString file = dir + fileName;
QFile loadFile(file);
if (!loadFile.open(QIODevice::ReadOnly))
{
qDebug() << "could't open projects json";
break;
}
QByteArray allData = loadFile.readAll();
loadFile.close();
//set QJsonDocument
QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(allData, &jsonError); //函数说明:解析UTF-8编码的JSON文档并从中创建QJsonDocument。
if (document.isNull() || (jsonError.error != QJsonParseError::NoError))
{
qDebug() << "document error";
break;
}
if (jsonError.error == QJsonParseError::IllegalUTF8String) //输入中出现非法UTF8序列
{
qDebug() << "An illegal UTF8 sequence occurred in the input";
break;
}
if (!document.isArray())
{
qDebug() << "document is not array";
break;
}
//read QJsonArray
QVector<double> indexVector;
QJsonArray array = document.array();
int size = array.size();
indexVector.clear();
for (int i = 0; i < size; ++i)
{
QJsonValue value = array.at(i);
if (value.type() == QJsonValue::Double)
{
double indexValue = value.toDouble();
indexVector.push_back(indexValue);
}
}
this->m_vector = indexVector;
result = true;
}while(false);
return result;
}
bool CJsonIO2::WriteJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
//set QJsonArray
QJsonArray json;
QVector<double>::iterator iter;
for (iter = m_vector.begin(); iter != m_vector.end(); ++iter)
{
json.append(*iter);
}
//set QJsonDocument
QJsonDocument doc(json);
QByteArray byteArray = doc.toJson();
//write document
QString strFile = dir + fileName;
QFile loadFile(strFile);
if (!loadFile.open(QIODevice::WriteOnly))
{
qDebug() << "could't open projects json";
break;
}
loadFile.write(byteArray);
loadFile.close();
result = true;
}while(false);
return result;
}
void CJsonIO2::PrintCurJson()
{
QVector<double>::const_iterator iter = this->m_vector.constBegin();
while (iter != this->m_vector.constEnd())
{
qDebug() << "value:" << *iter;
++iter;
}
}
void CJsonIO2::Init()
{
this->ReadJson("./", "read2.json");
}
main
#include <QCoreApplication>
#include "CJsonIO2.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//json2
CJsonIO2 *json2 = CJsonIO2::GetInstance();
QString dir2 = "./";
QString readName2 = "read2.json";
QString writeFile2 = "write2.json";
json2->ReadJson(dir2, readName2);
json2->WriteJson(dir2, writeFile2);
json2->PrintCurJson();
return a.exec();
}
七、完整示例三 (一个 json 对象含多个数组)
1. json 文件格式
{
"case1":
[
"one",
"two"
],
"case2":
[
"three",
"four"
]
}2. 保存容器
QHash<QString, QStringList>3. 提供单例模式
CJsonIO3.h
#ifndef CJSONIO3_H
#define CJSONIO3_H
#include <QHash>
class CJsonIO3
{
public:
static CJsonIO3* GetInstance();
bool ReadJson(const QString& dir, const QString& fileName);
bool WriteJson(const QString& dir, const QString& fileName);
void PrintCurJson();
QStringList GetValue(QString key);
private:
CJsonIO3();
~CJsonIO3();
void Init();
private:
static CJsonIO3 m_jsonIO;
QHash<QString, QStringList> m_hash; //存储当前json
QHash<QString, QStringList> m_defaultHash; //存储默认json
};
#endif // CJSONIO3_H
CJsonIO3.cpp
#include "CJsonIO3.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonArray>
#include <QFile>
#include <QDebug>
CJsonIO3 CJsonIO3::m_jsonIO;
CJsonIO3::CJsonIO3()
:m_hash()
,m_defaultHash()
{
this->Init();
}
CJsonIO3::~CJsonIO3()
{
}
CJsonIO3 *CJsonIO3::GetInstance()
{
return &m_jsonIO;
}
bool CJsonIO3::ReadJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
//read document
QString file = dir + fileName;
QFile loadFile(file);
if (!loadFile.open(QIODevice::ReadOnly))
{
qDebug() << "could't open projects json";
break;
}
QByteArray allData = loadFile.readAll();
loadFile.close();
//set QJsonDocument
QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(allData, &jsonError); //函数说明:解析UTF-8编码的JSON文档并从中创建QJsonDocument。
if (document.isNull() || (jsonError.error != QJsonParseError::NoError))
{
qDebug() << "document error";
break;
}
if (jsonError.error == QJsonParseError::IllegalUTF8String) //输入中出现非法UTF8序列
{
qDebug() << "An illegal UTF8 sequence occurred in the input";
break;
}
if (!document.isObject())
{
qDebug() << "document is not object";
break;
}
//read QJson
QHash<QString, QStringList> indexHash;
QStringList indexList;
QStringList keys = document.object().keys();
QJsonObject object = document.object();
int keySize = keys.size();
for (int i = 0; i < keySize; ++i)
{
QString strKey = keys.at(i);
indexList.clear();
if (object.contains(strKey))
{
QJsonValue value = object.value(strKey);
if (value.isArray())
{
QJsonArray array = value.toArray();
int arrSize = array.size();
for (int i = 0; i < arrSize; ++i)
{
QJsonValue arrValue = array.at(i);
if (arrValue.isString())
{
QString strValue = arrValue.toString();
indexList.push_back(strValue);
}
}
}
indexHash.insert(strKey, indexList);
}
}
this->m_hash = indexHash;
this->m_defaultHash = indexHash;
result = true;
}while(false);
return result;
}
bool CJsonIO3::WriteJson(const QString &dir, const QString &fileName)
{
bool result = false;
do
{
//set QJson
QJsonObject jsonObject;
QHash<QString,QStringList>::const_iterator iter = this->m_hash.constBegin();
while (iter != this->m_hash.constEnd())
{
QJsonArray jsonArray;
QString key = iter.key();
QStringList valueList = iter.value();
QStringList::const_iterator listIter = valueList.begin();
while (listIter != valueList.end())
{
jsonArray.append(*listIter);
++listIter;
}
jsonObject.insert(key, QJsonValue(jsonArray));
++iter;
}
//set QJsonDocument
QJsonDocument doc(jsonObject);
QByteArray byteArray = doc.toJson();
//write document
QString strFile = dir + fileName;
QFile loadFile(strFile);
if (!loadFile.open(QIODevice::WriteOnly))
{
qDebug() << "could't open projects json";
break;
}
loadFile.write(byteArray);
loadFile.close();
result = true;
}while(false);
return result;
}
void CJsonIO3::PrintCurJson()
{
QHash<QString,QStringList>::const_iterator iter = this->m_hash.constBegin();
while (iter != this->m_hash.constEnd())
{
QString key = iter.key();
QStringList valueList = iter.value();
qDebug() << "key:" << key << ": ";
QStringList::const_iterator listIter = valueList.begin();
while (listIter != valueList.end())
{
qDebug() << "value:" << *listIter;
++listIter;
}
++iter;
}
}
QStringList CJsonIO3::GetValue(QString key)
{
QStringList valueList;
QHash<QString, QStringList>::const_iterator iter = this->m_hash.constBegin();
while (iter != this->m_hash.constEnd())
{
QString hashKey = iter.key();
if (hashKey == key)
{
valueList = iter.value();
}
++iter;
}
return valueList;
}
void CJsonIO3::Init()
{
this->ReadJson("./", "read3.json");
}
main
#include <QCoreApplication>
#include "CJsonIO.h"
#include "CJsonIO2.h"
#include "CJsonIO3.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//json3
CJsonIO3 *json3 = CJsonIO3::GetInstance();
QString dir3 = "./";
QString readName3 = "read3.json";
QString writeFile3 = "write3.json";
json3->ReadJson(dir3, readName3);
json3->WriteJson(dir3, writeFile3);
json3->PrintCurJson();
return a.exec();
}