寫入Json 物件:
#include<QCoreApplication>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonValue>
#include<QJsonArray>
#include<QDebug>
int main(int argc,char * argv[]) {
QCoreApplication a(argc,argv);
QJsonObject jsonObj;
jsonObj.insert("A","aaa");
jsonObj.insert("B","bbb");
//輸出:
QJsonDocument doc(jsonObj);
QString strJson(doc.toJson());
qDebug()<<strJson.toStdString().data();
return a.exec();
}
輸出結果:

----------------------------------------------------------------------------------------------------------
Json 物件單行輸出:
#include<QCoreApplication>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonValue>
#include<QJsonArray>
#include<QDebug>
int main(int argc, char * argv[]){
QCoreApplication a(argc,argv);
QJsonObject jsonObj;
jsonObj.insert("A","aaa");
jsonObj.insert("B","bbb");
//輸出:
QJsonDocument doc(jsonObj);
QString strJson(doc.toJson(QJsonDocument::Compact));
qDebug()<<strJson.toStdString().data();
return a.exec();
}
輸出結果:

----------------------------------------------------------------------------------------------------------
Json 巢狀物件:
#include<QCoreApplication>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonValue>
#include<QJsonArray>
#include<QDebug>
int main(int argc, char * argv[]){
QCoreApplication a(argc,argv);
QJsonObject country;
country.insert("Japan","HelloKitty");
QJsonObject city;
city.insert("Taipei","101");
country.insert("Taiwan",city);
//輸出:
QJsonDocument doc(country);
QString strJson(doc.toJson(QJsonDocument::Compact));
qDebug()<<strJson.toStdString().data();
return a.exec();
}
輸出結果:
----------------------------------------------------------------------------------------------------------
Json 陣列: