QT4中使用第三方库QJson解析JSON文件。
QT5新增加了处理JSON的类,类均以QJson开头,包含在QtCore模块中。
用到的头文件
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
json解析
1.
QByteArray jsonData = "[{\"id\":\"11\", \"name\":\"aaa\"},"
"{\"id\":\"22\", \"name\":\"bbb\"},"
"{\"id\":\"33\", \"name\":\"ccc\"}]"; QJsonParseError jsonError;
QJsonDocument jsonDoucment = QJsonDocument::fromJson(jsonData, &jsonError);
if(jsonError.error == QJsonParseError::NoError){ if(!(jsonDoucment.isNull()||jsonDoucment.isEmpty())){ QVariantList dataList=jsonDoucment.toVariant().toList();
foreach (QVariant data, dataList) {
QVariantMap dataMap=data.toMap();
qDebug()<<"id:"<<dataMap["id"].toString()<<"name:"<<dataMap["name"].toString();
}
} }else{ //检查错误类型
qDebug()<<"jsonError:"<<jsonError.errorString();
}
2.生成json
QJsonArray jsonArray;
QJsonObject jsonObj1;
jsonObj1.insert ("task_name","task1");
jsonObj1.insert ("task_status:","ok");
jsonObj1.insert ("task_time:","2019_3_26"); QJsonObject jsonObj2;
jsonObj2.insert ("task_name","task2");
jsonObj2.insert ("task_status:","error");
jsonObj2.insert ("task_time:","2019_3_27"); jsonArray.append (jsonObj1);
jsonArray.append (jsonObj2); qDebug()<<jsonArray;
QJsonArray([{"task_name":"task1","task_status:":"ok","task_time:":"2019_3_26"},{"task_name":"task2","task_status:":"error","task_time:":"2019_3_27"}])