先了解概念
使用{ ... }
可以叫做一个json对像,使用QJsonObject
这个类来处理
使用[ ... ]
可以叫做一个json数组,使用QJsonArray
这个类来处理
QJsonDocument
保存/初始化 json对像, QJsonValue
保存json项目值
解析json
假如有以下QByteArray
字符串jsonstring
,内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
{ "cmd": "sourceInfo", "inport": 5, "source": [ { "id": 1000, "alias": "PC1_1080P", "url": "rtsp://192.168.10.183:8554/main", "username": "NULL", "password": "NULL", "codeInfo": "h264", "status": "online", "encode": "h264" }, { "id": 1001, "alias": "PC1_4K", "url": "rtsp://192.168.10.183:8555/4K", "username": "NULL", "password": "NULL", "codeInfo": "h264", "status": "online", "encode": "h265" } ] } |
表示此json数据里有 cmd inport source三个项目,其中source还是一个数组,这个数组中包含两个json对像
获取相对应的值
首先我们将这个字符串转换为json对像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
QJsonParseError error; QJsonDocument json = QJsonDocument::fromJson(jsonstring.toUtf8(), &error); if (error.error == QJsonParseError::NoError) { if (json.isObject()) // 是否是一个json对像,即 { ... } { QJsonObject jsonObject = json.object(); // 使用 value("cmd").toString() 来获取值 qDebug() << jsonObject.value("cmd").toString(); // 将会得到 "sourceInfo" } } else { qDebug() << error.errorString().toUtf8().constData(); } |
获取数组中的值
1 2 3 4 5 6 7 8 9 10 11 12 |
//QJsonDocument json = QJsonDocument::fromJson(jsonstring.toUtf8(), &error); //接上面的代码 //QJsonObject jsonObject = json.object(); uint32_t port = jsonObject.value("inport").toInt();// 获取到inport的值 QJsonValue value = jsonObject.value("source");//获取取source的值 if( !value.isArray() ) {...} // 判断这个值是不是一个数组 QJsonArray array = value.toArray(); // 使用 QJsonArray 来保存这个数组 for (int i = 0; i < array.size(); ++i) { QJsonObject sourceJson = array.at(i).toObject(); // 数组里每个值都是一个json对像 int xxx = sourceJson.value("id").toInt(); //取对像中的值 } |
生成JSON
简单应用
1 2 3 4 5 6 |
QJsonObject json; json.insert("cmd", "getSourceInfo"); json.insert("id", 0); QJsonDocument doc(json); conn->sendStr( doc.toJson() ); |
带有数组的,并保存到文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
QJsonArray array; QJsonObject json; QByteArray data; QFile file; foreach (sessions_t *i, sessionsList) { QJsonObject tmpObj; tmpObj.insert("ssid", (int)i->ssid); tmpObj.insert("inport", (int)i->inport); tmpObj.insert("url", i->url ); tmpObj.insert("x", i->x); tmpObj.insert("y", i->y); tmpObj.insert("w", i->w); tmpObj.insert("h", i->h); tmpObj.insert("alias", i->alias); tmpObj.insert("enable", i->enable); array.insert( 0,tmpObj); } json.insert("sessions", array ); QJsonDocument doc(json); data = doc.toJson(); file.setFileName(SESSION_FILE); file.open( QIODevice::WriteOnly | QIODevice::Text); file.write( data.constData() ); file.close(); |