Qt4 json读写案例
程序员文章站
2024-03-26 13:08:23
...
目录
一、前言
QT5新增加了处理JSON的类,类均以QJson开头,包含在QtCore模块中,所以直接使用就可以了
但是QT4仍需使用第三方库来解析JSON文件,本例使用的是C++的JSON类,网上有集成QT4的QJSON类也可以参考一下
二、效果展示
class.json文件:
三、源码简析
CJson类用于读写Json。
CJson.h
#ifndef CJSON_H
#define CJSON_H
#include <QFile>
#include "./json/json/json.h"
#include <QByteArray>
typedef struct stru_param
{
char name[64]; //学生姓名
int age; //年龄
int score; //成绩
char teacher[64]; //老师姓名
}stru_param;
typedef struct class_param{
int classcount; //班级的数目
stru_param params[64]; //每个班级的考试信息
class_param()
{
classcount = 0;
memset(¶ms, 0, sizeof(params));
}
}class_param;
class CJson
{
public:
CJson();
~CJson();
//读写class.json
int readJson(class_param *param);
int writeJson(const class_param ¶m);
private:
int getList(const Json::Value& valuelist, stru_param *listparam, int count);
};
#endif // CJSON_H
CJson.cpp
#include "CJson.h"
#include <QDebug>
#include <iostream>
#include <fstream>
#include <set>
#include <sstream>
#include <QString>
#define UCI_CONTU_GETBOOL(param, valnode, name, idx) \
if (!(valnode.isMember(#name) && valnode[#name].isBool())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
continue; \
} \
else \
{ \
param = valnode[#name].asBool(); \
}
#define UCI_CONTU_GETINT(param, valnode, name, idx) \
if (!(valnode.isMember(#name) && valnode[#name].isInt())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
continue; \
} \
else \
{ \
param = valnode[#name].asInt(); \
}
#define UCI_CONTU_GETDOUBLE(param, valnode, name, idx) \
if (!(valnode.isMember(#name) && valnode[#name].isDouble())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
continue; \
} \
else \
{ \
param = valnode[#name].asDouble(); \
}
#define UCI_CONTU_GETSTR(param, valnode, name, idx) \
if (!(valnode.isMember(#name) && valnode[#name].isString())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
continue; \
} \
else \
{ \
strncpy(param, valnode[#name].asCString(), sizeof(param)-1); \
}
#define UCI_DEFAULT_GETBOOL(param, valnode, name, idx, defaultval) \
if (!(valnode.isMember(#name) && valnode[#name].isBool())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
param = defaultval; \
} \
else \
{ \
param = valnode[#name].asBool(); \
}
#define UCI_DEFAULT_GETINT(param, valnode, name, idx, defaultval) \
if (!(valnode.isMember(#name) && valnode[#name].isInt())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
param = defaultval; \
} \
else \
{ \
param = valnode[#name].asInt(); \
}
#define UCI_DEFAULT_GETDOUBLE(param, valnode, name, idx, defaultval) \
if (!(valnode.isMember(#name) && valnode[#name].isDouble())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
param = defaultval; \
} \
else \
{ \
param = valnode[#name].asDouble(); \
}
#define UCI_DEFAULT_GETSTR(param, valnode, name, idx, defaultval) \
if (!(valnode.isMember(#name) && valnode[#name].isString())) \
{ \
qWarning("parse %s[%d].%s fail!", #valnode, idx, #name); \
strncpy(param, defaultval, sizeof(param)-1); \
} \
else \
{ \
strncpy(param, valnode[#name].asCString(), sizeof(param)-1); \
}
CJson::CJson()
{
}
CJson::~CJson()
{
}
int CJson::readJson(class_param *param)
{
std::ifstream ifs;
class_param parm;
int ret = 0;
char cfgpath[128];
//文件路径
strcpy(cfgpath, "./../class.json");
memset(&parm, 0 ,sizeof(parm));
try
{
//打开文件
ifs.open(cfgpath);
if (!ifs.is_open())
{
qWarning("open %s fail!", cfgpath);
return -1;
}
Json::Reader reader;
Json::Value root;
Json::Value sitelist;
if (!reader.parse(ifs, root, false))
{
qWarning("parse class.json fail!");
ifs.close();
return -2;
}
/*read class params*/
if (!(root.isMember("classlist") && root["classlist"].isArray()))
{
qWarning("parse class.json fail!");
ret = -3;
}
if (ret != 0)
{
qWarning("parse class.json err=%d!", ret);
ifs.close();
return ret;
}
sitelist = root["classlist"];
//获取各个班级的考试信息,班级数量
parm.classcount = getList(sitelist, parm.params, 128);
*param = parm;
}
catch(...)
{
qWarning("parse class.json except!");
ret = -7;
}
if (ifs.is_open())
{
ifs.close();
}
return ret;
}
int CJson::writeJson(const class_param ¶m)
{
std::ifstream ifs;
int ret = 0;
char cfgpath[128];
//文件路径
strcpy(cfgpath, "./../class.json");
try
{
//打开文件
ifs.open(cfgpath);
if (!ifs.is_open())
{
qWarning("open %s fail!", cfgpath);
return -1;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root,false))
{
qWarning("parse class.json fail!");
ifs.close();
return -2;
}
Json::Value arrayNew;
//暂存新信息
for(int i = 0; i < param.classcount; i++)
{
arrayNew[i] = root["classlist"][i];
arrayNew[i]["name"] = Json::Value(param.params[i].name);
arrayNew[i]["age"] = Json::Value(param.params[i].age);
arrayNew[i]["score"] = Json::Value(param.params[i].score);
arrayNew[i]["teacher"] = Json::Value(param.params[i].teacher);
}
//保存新信息
root["classlist"].clear();
for (int i = 0; i < param.classcount; i++)
{
root["classlist"].append(arrayNew[i]);
}
ifs.close();
//写入文本
std::ofstream o_file(cfgpath);
Json::StyledWriter fw;
fw.write(root);
o_file<<fw.write(root);
o_file.close();
}
catch(...)
{
qWarning("parse class.json except!");
ret = -7;
}
return 0;
}
int CJson::getList(const Json::Value &valuelist, stru_param *listparam, int count)
{
int readcount = 0;
int validcount = 0;
Json::Value valueInfo;
stru_param paramCfg;
readcount = valuelist.size();
for(int i=0; i<readcount; i++)
{
if (validcount >= count)
{
break;
}
valueInfo = valuelist[i];
//赋值
UCI_DEFAULT_GETSTR(paramCfg.name, valueInfo, name, i, "");
UCI_CONTU_GETINT(paramCfg.age, valueInfo, age, i);
UCI_CONTU_GETINT(paramCfg.score, valueInfo, score, i);
UCI_DEFAULT_GETSTR(paramCfg.teacher, valueInfo, teacher, i, "");
listparam[validcount] = paramCfg;
validcount++;
}
return validcount;
}
下面是简单的使用案例:
class_param param;
//先读原来的json值
CJson json;
json.readJson(¶m);
//修改前的信息
qDebug() << QString("Before:");
for(int i=0; i<param.classcount; i++)
{
qDebug() << QString("name:%1; age:%2; score:%3; teacher:%4")
.arg(param.params[i].name).arg(param.params[i].age)
.arg(param.params[i].score).arg(param.params[i].teacher);
}
//修改json
param.classcount++;
strcpy(param.params[param.classcount-1].name, "JJ");
param.params[param.classcount-1].age = 18;
param.params[param.classcount-1].score = 100;
strcpy(param.params[param.classcount-1].teacher, "Martin");
json.writeJson(param);
//修改后的信息
json.readJson(¶m);
qDebug() << QString("After:");
for(int i=0; i<param.classcount; i++)
{
qDebug() << QString("name:%1; age:%2; score:%3; teacher:%4")
.arg(param.params[i].name).arg(param.params[i].age)
.arg(param.params[i].score).arg(param.params[i].teacher);
}
四、源码
链接:https://pan.baidu.com/s/1OKFj-o9TefYFa6sAs-4FRw
提取码:9szh