Qtワークノート-Qt 5 QJsonを利用してファイルからJsonを読み取り解析する


原文住所:
https://blog.csdn.net/hp_cpp/article/details/80338116
 
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"
    ]
}

ローカルディスクに保存します.QJsonを利用すれば解析が容易にできる.
   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();

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

    //         JSON    ,          
    if(rootObj.contains("first fruit"))
    {
       QJsonObject subObj = rootObj.value("first fruit").toObject();
       qDebug() << "describe is:" << subObj["describe"].toString();
       qDebug() << "icon is:" << subObj["icon"].toString();
       qDebug() << "name is:" << subObj["name"].toString();
    }

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

    if(rootObj.contains("three fruit array"))
    {
       QJsonArray subArray = rootObj.value("three fruit array").toArray();
       for(int i = 0; i< subArray.size(); i++)
       {
           qDebug() << i<

必要なヘッダファイル:
#include 
#include 
#include 
#include 
#include 
#include 

実行結果:
key 0  is: "first fruit"
key 1  is: "second fruit"
key 2  is: "three fruit array"
describe is: "an apple"
icon is: "appleIcon"
name is: "apple"
describe is: "an orange"
icon is: "orangeIcon"
name is: "orange"
0  value is: "eat 0"
1  value is: "eat 1"
2  value is: "eat 2"
3  value is: "eat 3"
4  value is: "eat 4"