본문 바로가기
놀기/Qt

[QT] Json array 읽기

by Hi~ 2023. 3. 4.

아래와 같은 Json array 읽기 예제

 

 

QT의 Json Class를 사용해서 아래와 같이 쉽게 읽을 수 있음.

 

 

예제 코드

#include <QCoreApplication>
#include <QTimer>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

#if 0
{
  "name" : "busyman",
  "yyyymmdd" : "19850101",
  "list" : [
    {
      "name" : "apple",
      "price" : 9900
    },

    {
      "name" : "banana",
      "price" : 5000
    }
    ]
}
#endif

class fruitInfo {
public:
    fruitInfo() {
        price = 0;
    }
    ~fruitInfo() {}

    QJsonObject toJson() const {
        return {{"name", name}, {"price", price}};
    }

public:
    QString name;
    int price;
};

void run_main(void)
{
    qDebug() << "===== QT Ex. : Read JSON String =====";

    QString jsonString = "{\"name\":\"busyman\",\"yyyymmdd\":\"19850101\",\"list\":[{\"name\":\"apple\",\"price\":9900},{\"name\":\"banana\",\"price\":5000}]}";

    QJsonDocument jsonDoc  = QJsonDocument::fromJson(QByteArray(jsonString.toLocal8Bit().constData()));
    QJsonObject jsonData = jsonDoc.object();

    QString json_name = jsonData["name"].toString();
    QString json_yyyymmdd = jsonData["yyyymmdd"].toString();
    QJsonArray jsonArray_list = jsonData["list"].toArray();

    qDebug() << "name:" << json_name;
    qDebug() << "yyyymmdd:" << json_yyyymmdd;
    qDebug() << "list:" << jsonArray_list;
    qDebug();

    foreach (const QJsonValue & value, jsonArray_list) {
        QJsonObject obj = value.toObject();

        QString name = obj["name"].toString();
        int price = obj["price"].toInt();

        fruitInfo* pFruitInfo = new fruitInfo();
        pFruitInfo->name = name;
        pFruitInfo->price = price;

        qDebug() << pFruitInfo->toJson();

        delete pFruitInfo;
    }
}

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

    QTimer::singleShot(0,[](){
         run_main();
         QCoreApplication::exit(0);
    });

    return a.exec();
}

 

 

실행 결과

===== QT Ex. : Read JSON String =====
name: "busyman"
yyyymmdd: "19850101"
list: QJsonArray([{"name":"apple","price":9900},{"name":"banana","price":5000}])

QJsonObject({"name":"apple","price":9900})
QJsonObject({"name":"banana","price":5000})

 

 

json_read.pro
0.00MB
main.cpp
0.00MB

댓글