C++ qt 使用jsoncpp json 讀寫操作

JsonCpp的使用

項目需要c++下使用json,我選擇瞭JsonCpp,官網是:https://github.com/open-source-parsers/jsoncpp
解壓後使用python編譯出兩個h文件和一個cpp文件:

(電腦需要安裝python自己百度安裝,這裡就不說瞭)

安裝python後,打開windows下cmd窗口,進入到jsoncpp文件夾  如圖:

執行命令: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工程下載地址:點擊此處下載

到此這篇關於C++ qt 使用jsoncpp json 讀寫的文章就介紹到這瞭,更多相關C++ qt 使用jsoncpp json內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: