QT-json文件
QTjson文件的简单使用
一、创建和写入json文件
1、引用的头文件
#include <QJsonObject>
#include <QJsonDocument>
2、数据转json代码
//1.创建json对象
QJsonObject info;
info.insert("name", "xiaoming");
info.insert("age", 18);
info.insert("height", 185);
info.insert("weight", "75Kg");
QJsonObject jsoninfo;
jsoninfo.insert("code", 1);
jsoninfo.insert("info", "个人信息");
jsoninfo.insert("data", info);
//2.创建json文档
QJsonDocument jsondoc;
jsondoc.setObject(jsoninfo);
QFile qfile("./info.json");
if(qfile.open(QIODevice::WriteOnly)){
qfile.write(jsondoc.toJson());
qfile.close();
qDebug()<<"写入json文件成功";
QMessageBox::information(this, "json", "信息写入json文件成功");
}else{
QMessageBox::warning(this, "写入文件", "文件打开失败");
}
二、读取json文件
QString strjson;
QFile qfile("./info.json");
if(qfile.open(QIODevice::ReadOnly)){
strjson = qfile.readAll();
qfile.close();
}else{
QMessageBox::warning(this, "读取文件", "文件打开失败");
exit(1);
}
QJsonParseError parseerr; //返回解析错误的报告信息
QJsonDocument jsoninfo = QJsonDocument::fromJson(strjson.toUtf8(), &parseerr);
if(!jsoninfo.isEmpty() && (parseerr.error == QJsonParseError::NoError)){
//返回的json不为空,没有解析错误
//转为json对象
QJsonObject json = jsoninfo.object();
QJsonValue code = json.value("code");
QJsonValue data = json.value("data");
if(code.isUndefined() || code.toDouble() != 1 || data.isUndefined() || !data.isObject()){
QMessageBox::warning(this, "wearing", "json数据转换错误");
exit(100);
}
QJsonObject info = data.toObject();
/*
info.insert("name", "xiaoming");
info.insert("age", 18);
info.insert("height", 185);
info.insert("weight", "75Kg");
*/
QJsonValue name = info.value("name");
QJsonValue age = info.value("age");
QJsonValue height = info.value("height");
QJsonValue weight = info.value("weight");
if(name.isUndefined() ||
age.isUndefined()||
height.isUndefined()||
weight.isUndefined()){
QMessageBox::critical(this, "error", "接口错误");
exit(100);
}
QString strname = name.toString();
int intage = age.toInt();
int intheight = height.toInt();
int intweight = weight.toInt();
QString strinfo = "info:";
strinfo += "\nname:"+strname;
strinfo += "\nage:"+QString::number(intage, 10);
strinfo += "\nintheight:"+QString::number(intheight, 10);
strinfo += "\nintweight:"+QString::number(intweight, 10);
QMessageBox::information(this, "infotojson", strinfo, QMessageBox::Yes);
}else{
QMessageBox::warning(this, "str2jsondoc", "json解析失败");
exit(100);
}
原文地址:https://blog.csdn.net/qq_57041630/article/details/143554002
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!