QT 有专门对于json字符串得处理类QJsonDocument相关类。
下面是一种我常用的json解析
1.Json解析 读取
QJsonParseError error;
QJsonDocument document = QJsonDocument::fromJson(data.toUtf8(), &error);
if(QJsonParseError::noError == error.error)
{
//map
QVariantMap map = document.toVariant().toMap();
if(map.contains("address"))
{
QString addr = map["address"].toString();
}
//数组
QList<QVariant> list = document.toVariant.toList();
foreach(QVariant item, list)
{
QVariantMap map = item.toMap();
QString addr = map["address"].toString();
}
}
2.Json 写入
QVariantMap map;
map["address"] = QString("192.168.0.1");
map["name"] = QString("xie");
QString data = QJsonDocument::fromVariant(map).toJson(QJsonDocument::Indented);//带有格式。
QJsonDocument::Compact(没有格式)
用法
请求JSON
UpdataVersion::UpdataVersion(QObject *parent) : QObject(parent)
{
//JSON url
QString url = "";
QNetworkRequest request;
request.setUrl(QUrl(url));
QNetworkAccessManager *manger = new QNetworkAccessManager(this);
QNetworkReply* reply = manger->get(request);//发送get请求
// connect(manger, &QNetworkAccessManager::finished, this, &UpdataVersion::onReplyFinished);
//使用同步,再得到版本号后才进行后面的动作
QEventLoop loop;
connect(manger, &QNetworkAccessManager::finished,&loop, &QEventLoop::quit);
loop.exec();
onReplyFinished(reply);//传json数据
}
解析
void UpdataVersion::onReplyFinished(QNetworkReply *reply)
{
QByteArray arr = reply->readAll();
qDebug()<<"get:"<<arr;
// get: "{"v_app":4,"v_library":2,"v_example":2,"md5_app_update":"2020-09-26"}"
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(arr,&error);
if(error.error != QJsonParseError::NoError){
qDebug()<<"parse json error";
}
//map json解析
QVariantMap map = doc.toVariant().toMap();
if(map.contains("v_app")){
m_appVersion=map["v_app"].toString();
}
if(map.contains("v_library")){
m_libVersion = map["v_library"].toString();
}
if(map.contains("v_example")){
m_exampleVersion = map["v_example"].toString();
}
if(map.contains("md5_app_update")){
m_appUpdatefileMD5 = map["md5_app_update"].toString();
}
}