Qt解析JSON數組

JSON 數組在中括號中書寫,以逗號分隔。

JSON 中數組值必須是合法的 JSON 數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)。

比如:

[
    {
        "id": "1",
        "name": "aa"
    },
    {
        "id": "2",
        "name": "bb"
    }
]

Qt解析方式:

    QByteArray array = "[{\"name\": \"aa\",\"age\": \"20\"},{\"name\": \"bb\",\"age\": \"25\"}]";


    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(array,&error);
    if(error.error != QJsonParseError::NoError)
    {
        qInfo()<<"parse json error"<<error.errorString();
        return;
    }

    if(document.isNull()||document.isEmpty())
    {
        qInfo()<<"parse json null or empty";
        return;
    }

    QVariantList list = document.toVariant().toList();
    for(int i = 0; i<list.count(); i++)
    {
        QVariantMap map = list[i].toMap();
        qInfo()<<map["name"].toString();
        qInfo()<<map["age"].toString();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章