Qt工作笔记-Qt5 利用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<<" value is:" << subArray.at(i).toString();
       }
    }

需要包含的头文件:

#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"


 

你可能感兴趣的:(C/C++,Qt,工作笔记)