QT的Json格式讀寫修改

@TOC
大部分參考博客
不過(guò)由于修改json的方式存在問(wèn)題亲善,我這邊修改了一下激涤,可以運(yùn)行了。
可以用作配置相關(guān)運(yùn)行參數(shù)了

使用方式

使用qtcreator新建工程沐批,直接替換main.c中代碼即可編譯運(yùn)行。

效果

原來(lái)json內(nèi)容如下

{
    "class": [
        {
            "age": "18",
            "home": "xx",
            "name": "aron566"
        },
        {
            "age": "19",
            "home": "xx",
            "name": "aron566"
        }
    ]
}

修改后:

{
    "class": [
        {
            "age": "45",
            "home": "xx",
            "name": "aron566"
        },
        {
            "age": "19",
            "home": "xx",
            "name": "aron566"
        }
    ]
}

測(cè)試源碼

#include "mainwindow.h"
#include <QApplication>

int ReadJson(int argc, char *argv[]);
int WriteJson(int argc, char *argv[]);
int WriteJsonx(int argc, char *argv[]);
int ModifiedJson(int argc, char *argv[]);

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    WriteJsonx(argc, argv);
//    ReadJson(argc, argv);
    ModifiedJson(argc, argv);
    return 0;
//    MainWindow w;
//    w.show();
//    return a.exec();
}

/*
讀取json
{
    "name": "aron566",
    "age": "18",
    "home": "xx"
}
*/
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
/*
讀取json
{
    "name": "aron566",
    "age": "18",
    "home": "xx"
}
*/
/*讀取json格式數(shù)據(jù)*/
int ReadJson(int argc, char *argv[])
{
//    QCoreApplication a(argc, argv);

    QFile file("test.json");
    if(!file.open(QIODevice::ReadOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }

    QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
    QJsonObject obj = jdc.object();
    qDebug() << obj.value("name").toString()
             << obj.value("age").toString()
             << obj.value("home").toString();
    return 0;
}

/*寫出json格式數(shù)據(jù)*/
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>

int WriteJson(int argc, char *argv[])
{
//    QCoreApplication a(argc, argv);

    QFile file("test.json");
    if(!file.open(QIODevice::WriteOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }

    QJsonObject obj;
    obj["age"] = "18";
    obj["name"] = "aron566";
    obj.insert("home", "xx");
    QJsonDocument jdoc(obj);
    file.write(jdoc.toJson());
    file.flush();
    return 0;
}

#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
/*使用QJsonArray*/
/*
{
    "class": [
        {
            "age": "18",
            "home": "xx",
            "name": "aron566"
        },
        {
            "age": "19",
            "home": "xx",
            "name": "aron566"
        }
    ]
}
*/
int WriteJsonx(int argc, char *argv[])
{
//    QCoreApplication a(argc, argv);

    QFile file("test.json");
    if(!file.open(QIODevice::WriteOnly)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }

    QJsonObject rootObj;

    QJsonObject obj;
    obj["age"] = "18";
    obj["name"] = "aron566";
    obj.insert("home", "xx");

    QJsonObject obj1;
    obj1["age"] = "19";
    obj1["name"] = "aron566";
    obj1.insert("home", "xx");

    QJsonArray classArray;
    classArray.append(obj);
    classArray.append(obj1);

    rootObj["class"] = classArray;

    QJsonDocument jdoc(rootObj);
    file.write(jdoc.toJson());
    file.flush();
    return 0;
}

/*修改Json數(shù)據(jù)*/
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
/*先讀,修改,再寫*/
int ModifiedJson(int argc, char *argv[])
{
//    QCoreApplication a(argc, argv);

    QFile file("test.json");
    if(!file.open(QIODevice::ReadWrite)) {
        qDebug() << "File open failed!";
    } else {
        qDebug() <<"File open successfully!";
    }

    QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
    QJsonObject rootObj = jdc.object();
    QJsonObject subObj;
    QJsonArray subArray;
    /*判斷是否是數(shù)組*/
    if(rootObj.contains("class") && rootObj["class"].isArray())
    {
        qDebug() << "check array is ok!";
        subArray = rootObj.value("class").toArray();

        qDebug() << "數(shù)組長(zhǎng)度大猩贰:" << subArray.size();


        for(int i = 0; i< subArray.size(); i++)
        {
            /*轉(zhuǎn)換為子對(duì)象*/
            subObj = subArray.at(i).toObject();

            if (subObj.contains("age") && subObj["age"].isString())
            {
                qDebug() << "age is:" << subObj["age"].toString();
            }
            if (subObj.contains("home") && subObj["home"].isString())
            {
                qDebug() << "home is:" << subObj["home"].toString();
            }
            if (subObj.contains("name") && subObj["name"].isString())
            {
                qDebug() << "name is:" << subObj["name"].toString();
            }

            if(subObj["age"].toString() == "18")
            {
                qDebug() << "寫入 age 45";

                /*兩種方式更換age這個(gè)對(duì)應(yīng)值*/
                subObj["age"] = "25";/**< 第一種*/
                subObj.remove("age");/**< 第二種先移除*/
                subObj.insert("age" ,"45");/**< 第二種再插入*/
                subArray.replace(i ,subObj);
                rootObj.insert("class" ,subArray);
            }
        }
    }

    jdc.setObject(rootObj);
    file.seek(0);/*從頭開(kāi)始寫*/
    file.write(jdc.toJson());
    file.flush();
    return 0;
}

/*
 * JSON格式如下:
{
    "first fruit":
    {
        "describe":"an apple",
        "icon":"appleIcon",
        "name":"apple"
    },
    "second fruit":
    {
        "describe":"an orange",
        "icon":"orangeIcon",
        "name":"orange"
    },
    "three fruit array":
    [
        "eat 0",
        "eat 1",
        "eat 2",
        "eat 3",
        "eat 4"
    ]
}

解析:
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QJsonObject>
#include <QDebug>
#include <QJsonArray>
void read()
{
    QFile loadFile("D:\\1.json");

    if(!loadFile.open(QIODevice::ReadOnly))
    {
        qDebug() << "could't open projects json";
        return;
    }

    QByteArray allData = loadFile.readAll();
    loadFile.close();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));

    if(json_error.error != QJsonParseError::NoError)
    {
        qDebug() << "json error!";
        return;
    }

    QJsonObject rootObj = jsonDoc.object();

    QStringList keys = rootObj.keys();
    for(int i = 0; i < keys.size(); i++)
    {
        qDebug() << "key" << i << " is:" << keys.at(i);
    }

    //因?yàn)槭穷A(yù)先定義好的JSON數(shù)據(jù)格式,所以這里可以這樣讀取
    if(rootObj.contains("first fruit") && rootObj["first fruit"].isObject())
    {
        QJsonObject subObj = rootObj["first fruit"].toObject();
        if (subObj.contains("describe") && subObj["describe"].isString())
        {
            qDebug() << "describe is:" << subObj["describe"].toString();
        }
        if (subObj.contains("icon") && subObj["icon"].isString())
        {
            qDebug() << "icon is:" << subObj["icon"].toString();
        }
        if (subObj.contains("name") && subObj["name"].isString())
        {
            qDebug() << "name is:" << subObj["name"].toString();
        }
    }

    if(rootObj.contains("second fruit") && rootObj["second fruit"].isObject())
    {
        QJsonObject subObj = rootObj["second fruit"].toObject();
        if (subObj.contains("describe") && subObj["describe"].isString())
        {
            qDebug() << "describe is:" << subObj["describe"].toString();
        }
        if (subObj.contains("icon") && subObj["icon"].isString())
        {
            qDebug() << "icon is:" << subObj["icon"].toString();
        }
        if (subObj.contains("name") && subObj["name"].isString())
        {
            qDebug() << "name is:" << subObj["name"].toString();
        }
    }

    if(rootObj.contains("three fruit array") && rootObj["three fruit array"].isArray())
    {
        QJsonArray subArray = rootObj.value("three fruit array").toArray();
        for(int i = 0; i< subArray.size(); i++)
        {
            if (subArray[i].isString())
            {
                qDebug() << i<<" value is:" << subArray.at(i).toString();
            }
        }
    }
}
*/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末耻陕,一起剝皮案震驚了整個(gè)濱河市拙徽,隨后出現(xiàn)的幾起案子刨沦,更是在濱河造成了極大的恐慌诗宣,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件想诅,死亡現(xiàn)場(chǎng)離奇詭異召庞,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)来破,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門篮灼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人徘禁,你說(shuō)我怎么就攤上這事诅诱。” “怎么了送朱?”我有些...
    開(kāi)封第一講書人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵娘荡,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我驶沼,道長(zhǎng)炮沐,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任回怜,我火速辦了婚禮大年,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己翔试,他們只是感情好轻要,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著垦缅,像睡著了一般伦腐。 火紅的嫁衣襯著肌膚如雪秆麸。 梳的紋絲不亂的頭發(fā)上蹬屹,一...
    開(kāi)封第一講書人閱讀 51,698評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音空镜,去河邊找鬼粹庞。 笑死咳焚,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的庞溜。 我是一名探鬼主播革半,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼流码!你這毒婦竟也來(lái)了又官?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤漫试,失蹤者是張志新(化名)和其女友劉穎六敬,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體驾荣,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡外构,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了播掷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片审编。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖歧匈,靈堂內(nèi)的尸體忽然破棺而出垒酬,到底是詐尸還是另有隱情,我是刑警寧澤件炉,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布勘究,位于F島的核電站,受9級(jí)特大地震影響妻率,放射性物質(zhì)發(fā)生泄漏乱顾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一宫静、第九天 我趴在偏房一處隱蔽的房頂上張望走净。 院中可真熱鬧券时,春花似錦、人聲如沸伏伯。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)说搅。三九已至炸枣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間弄唧,已是汗流浹背适肠。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留候引,地道東北人侯养。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像澄干,于是被迫代替她去往敵國(guó)和親逛揩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容