示例:从文件读取json
{ "appDesc": { "description": "SomeDescription", "message": "SomeMessage" }, "appName": { "description": "Home", "message": "Welcome", "imp":["awesome","best","good"] }}void readJson() { QString val; QFile file; file.setFileName("test.json"); file.open(QIODevice::Readonly | QIODevice::Text); val = file.readAll(); file.close(); qWarning() << val; QJsondocument d = QJsondocument::fromJson(val.toUtf8()); QJsonObject sett2 = d.object(); QJsonValue value = sett2.value(QString("appName")); qWarning() << value; QJsonObject item = value.toObject(); qWarning() << tr("QJsonObject of description: ") << item; qWarning() << tr("QJsonObject[appName] of description: ") << item["description"]; QJsonValue subobj = item["description"]; qWarning() << subobj.toString(); qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"]; QJsonArray test = item["imp"].toArray(); qWarning() << test[1].toString(); }输出值
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) "QJsonObject[appName] of description: " QJsonValue(string, "Home") "Home" "QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) "best"示例:从字符串读取json
将json分配给字符串,如下所示,并使用
readJson()前面显示的功能:
val = ' { "appDesc": { "description": "SomeDescription", "message": "SomeMessage" }, "appName": { "description": "Home", "message": "Welcome", "imp":["awesome","best","good"] } }';输出值
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) "QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) "QJsonObject[appName] of description: " QJsonValue(string, "Home") "Home" "QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) "best"


