C++ qt 使用jsoncpp json 讀寫操作
JsonCpp的使用
項目需要c++下使用json,我選擇了JsonCpp,官網(wǎng)是:https://github.com/open-source-parsers/jsoncpp。
解壓后使用python編譯出兩個h文件和一個cpp文件:
(電腦需要安裝python自己百度安裝,這里就不說了)
安裝python后,打開windows下cmd窗口,進入到j(luò)soncpp文件夾? 如圖:
執(zhí)行命令:python amalgamate.py 就會生成dist文件夾 里面有?json.h json-forwards.h jsoncpp.cpp三個文件:如下
將三個文件加入到工程即可使用,我是要qt進行測試使用:
main.cpp如下
#include <iostream> #include <fstream> #include "dist/json/json.h" using namespace std; int main(int argc, char *argv[]) { // write Json::Value people1; people1["name"] = "Dione"; people1["sex"] = "男"; people1["age"] = 24; people1["note"] = "jsoncpp write test!"; Json::Value people2; people2["name"] = "Hulis"; people2["sex"] = "女"; people2["age"] = 22; people2["note"] = "jsoncpp write test!"; Json::Value peoples; peoples.append(people1); peoples.append(people2); Json::Value writeValue; writeValue["classname"] = "三年一班"; writeValue["peoples"] = peoples; Json::FastWriter fwriter; std::string strf = fwriter.write(writeValue); std::ofstream ofsf("example_fast_writer.json"); ofsf << strf; ofsf.close(); Json::StyledWriter swriter; std::string strs = swriter.write(writeValue); std::ofstream ofss("example_styled_writer.json"); ofss << strs; ofss.close(); // read string strValue = "{\"key1\":\"111\",\"array\":[{\"key2\":\"222\"},{\"key2\":\"333\"},{\"key2\":\"444\"}]}"; Json::Reader reader; Json::Value root; if (reader.parse(strValue, root)) { std::string out = root["key1"].asString(); qDebug()<<QString::fromStdString(out); Json::Value arrayObj = root["array"]; for (int i=0; i<arrayObj.size(); i++) { out = arrayObj[i]["key2"].asString(); qDebug()<<QString::fromStdString(out); } } std::ifstream ifs("example_fast_writer.json"); if (reader.parse(ifs, root)) { std::string out = root["classname"].asString(); qDebug()<<QString::fromStdString(out); Json::Value peoples = root["peoples"]; for (int i=0; i<peoples.size(); i++) { qDebug()<<QString::fromStdString(peoples[i]["name"].asString()); qDebug()<<QString::fromStdString(peoples[i]["sex"].asString()); qDebug()<<QString::fromStdString(peoples[i]["age"].asString()); qDebug()<<QString::fromStdString(peoples[i]["note"].asString()); } } return 0; }
會生成兩個json文件,一個是沒有格式寫入一個是有格式寫入,如下:
Demo工程下載地址:點擊此處下載
到此這篇關(guān)于C++ qt 使用jsoncpp json 讀寫的文章就介紹到這了,更多相關(guān)C++ qt 使用jsoncpp json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Qt5.9實現(xiàn)簡單的多線程實例(類QThread)
Qt開啟多線程,主要用到類QThread。用一個類繼承QThread,然后重新改寫虛函數(shù)run()。具有一定的參考價值,感興趣的可以了解一下2021-09-09Linux?C/C++實現(xiàn)網(wǎng)絡(luò)流量分析工具
網(wǎng)絡(luò)流量分析的原理基于對數(shù)據(jù)包的捕獲、解析和統(tǒng)計分析,通過對網(wǎng)絡(luò)流量的細致觀察和分析,幫助管理員了解和優(yōu)化網(wǎng)絡(luò)的性能,本文將通過C++實現(xiàn)網(wǎng)絡(luò)流量分析工具,有需要的可以參考下2023-10-10VS2017+Qt5+Opencv3.4調(diào)用攝像頭拍照并存儲
本文主要介紹了VS2017+Qt5+Opencv3.4調(diào)用攝像頭拍照并存儲,實現(xiàn)了視頻,拍照,保存這三個功能。具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05