推薦答案
在Qt中使(shi)用(yong)JSON文件需要使(shi)用(yong)Qt的JSON庫(ku)(ku),這(zhe)個庫(ku)(ku)提供了一(yi)個叫做QJsonDocument的類(lei)來處理(li)JSON數(shu)據,其(qi)使(shi)用(yong)方(fang)法如(ru)下:
導入頭文件:
#include
#include
#include
創建(jian) JSON數(shu)據:
QJsonObject jsonObj;
jsonObj.insert("name", "John");
jsonObj.insert("age", 30);
jsonObj.insert("city", "New York");
QJsonArray jsonArray;
jsonArray.append("red");
jsonArray.append("green");
jsonArray.append("blue");
jsonObj.insert("colors", jsonArray);
QJsonDocument jsonDoc(jsonObj);
將JSON數據寫入文件:
QFile jsonFile("test.json");
if (jsonFile.open(QIODevice::WriteOnly)) {
jsonFile.write(jsonDoc.toJson());
jsonFile.close();
}
讀取JSON數據:
QFile jsonFile("test.json");
if (jsonFile.open(QIODevice::ReadOnly)) {
QByteArray data = jsonFile.readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
QJsonObject jsonObj = jsonDoc.object();
QString name = jsonObj["name"].toString();
int age = jsonObj["age"].toInt();
QString city = jsonObj["city"].toString();
QJsonArray jsonArray = jsonObj["colors"].toArray();
QString color1 = jsonArray.at(0).toString();
QString color2 = jsonArray.at(1).toString();
QString color3 = jsonArray.at(2).toString();
jsonFile.close();
}
上述代(dai)碼示例中(zhong)(zhong),我們首先創建了一個包含名(ming)字(zi)、年齡、城(cheng)市和顏色(se)數(shu)組的JSON對象,然后將其(qi)(qi)寫入test.json文件中(zhong)(zhong)。接(jie)著我們從test.json文件中(zhong)(zhong)讀取JSON數(shu)據,并提取出其(qi)(qi)中(zhong)(zhong)的字(zi)段和數(shu)組。
使用Qt的JSON庫,可(ke)以方(fang)便地處理JSON數(shu)據,使得我們能(neng)夠在Qt應用程序中輕松地使用JSON文件。
其他答案
-
JSON的全(quan)稱是(shi)”JavaScript Object Notation”,意思是(shi)JavaScript對象表示法,它是(shi)一種基于文本,獨立于語言的輕量(liang)級數據交換格(ge)式。JSON 解析器和 JSON 庫(ku)支持許多不同的編程語言,目(mu)前非常(chang)多的編程語言都支持JSON。
-
JSON有兩種(zhong)表示結構(gou)(gou),對象(xiang)和數組。l 對象(xiang)結構(gou)(gou)以(yi)”{”大(da)括號開始(shi),以(yi)”}”大(da)括號結束。中間部分(fen)由0或(huo)多個以(yi)”,”分(fen)隔(ge)的”key(關(guan)鍵(jian)字)/value(值)”對構(gou)(gou)成,關(guan)鍵(jian)字和值之間以(yi)”:”分(fen)隔(ge),語法結構(gou)(gou)如代碼。

熱問標簽 更多>>
大家都在(zai)問 更多>>
java合并(bing)兩個數組并(bing)升序排(pai)列怎(zen)么(me)...
java合并(bing)(bing)兩個(ge)數組并(bing)(bing)排序(xu)怎么操作
java多行字符串輸入怎(zen)么操作