Parse jsonarray?

前端 未结 2 1826
不思量自难忘°
不思量自难忘° 2021-02-04 08:26

I\'ve got an JSON like the following:

{
    \"agentsArray\": [{
        \"ID\": 570,
        \"picture\": \"03803.png\",
        \"name\": \"Bob\"
    }, {
              


        
2条回答
  •  时光说笑
    2021-02-04 09:15

    I would recommend using the QJson* classes from QtCore in Qt 5. They are very efficient due to the machine readable binary storage optimized for reading and writing, and it is also very convenient to use them due to the nice API they have.

    This code base works for me just fine, but please note that I neglected all the error checking for now which is not a good advice for production code. This is just a prototype code, respectively.

    main.json

    {
        "agentsArray": [{
            "ID": 570,
            "picture": "03803.png",
            "name": "Bob"
        }, {
            "ID": 571,
            "picture": "02103.png",
            "name": "Tina"
        }]
    }
    

    main.cpp

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        QFile file("main.json");
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray jsonData = file.readAll();
        file.close();
    
        QJsonDocument document = QJsonDocument::fromJson(jsonData);
        QJsonObject object = document.object();
    
        QJsonValue value = object.value("agentsArray");
        QJsonArray array = value.toArray();
        foreach (const QJsonValue & v, array)
            qDebug() << v.toObject().value("ID").toInt();
    
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    570 
    571 
    

提交回复
热议问题