2016-08-04 69 views
0

我想讀取如下面在QT中顯示的json文件。有人可以建議一種方法來從json對象獲取值並將它們存儲在單獨的容器或數組中,例如test_cell2.CELLS [0]或某種方式,以便嵌套也可以被照顧,並且我可以在解析文件後輕鬆訪問它們QT讀取JSON文件並存儲和重試值

"test_cells2" : { 
     "CELLS" : { 
      "cell_0" : { 
       "prettyName" : "cell_1", 
       "CELLS" : { 
        "cell_1" : { 
         "prettyName" : "cell_1", 
         "type" : "default", 
        }, 
       }, 
      }, 
      "cell_1" : { 
       "prettyName" : "cell_1", 
       "type" : "default", 
      }, 
      "cell_2" : { 
       "type" : "text cell ko", 
      }, 
      "cell_3" : { 
       "prettyName" : "cell_3", 
       "type" : "default", 
      }, 
      "cell_4" : { 
       "data" : { 
        "settings" : { 
         "EXEC_PARAMETERS" : { 
          "defaultQueue" : "batch", 
          "environment" : { 
           "blabla" : "blabla2", 
          }, 
         }, 
        }, 
       }, 
       "type" : "parallel_test", 
      }, 
     }, 
    }, 
+0

的[如何創建/讀/寫JSON在QT5文件(可能的複製http://stackoverflow.com/questions/15893040/how-to-create-read-write-json-files-in-qt5) –

回答

1

如果你的Qt版本> 5.5檢查QJSonDocument,http://doc.qt.io/qt-5/qjsondocument.html

一個例子:

// Just read it from a file... or copy here   
    const QString yourJSON = "..."; 
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(yourJSON.toLocal8Bit()); 
    const QVariantMap map = jsonDoc.toVariant().toMap(); 

要照顧內細胞的細胞嵌套的,第一次加載你的細胞陣列:

// Start read your parameter 
    const QVariant testCells2 = map["test_cells2"].toVariant(); 
    const QVariantList CELLS = testCells2.toList(); 
    // Now, we have a list available CELLS, check one be one 
    foreach (const QVariant& cell, CELLS) { 
     const QVariantMap wrapped = cell.toMap(); 
     qDebug() << "Pretty Name: " << wrapped["prettyName"].toString(); 
     qDebug() << "Type: " << wrapped["type"].toString(); 
     const hasList = !wrapped["CELLS"].toList().isEmpty(); 
     qDebug() << "Has child list? << hasList; 
     if (hasList) { 
      // Start another loop to check the child list. 
     } 
    } 
+0

如何照顧嵌套在CELLS中的CELLS – leo

+0

我添加了一些更改以使用QVariant,QVariantList,QVariantMap,您也可以使用QJsonObject。 – mohabouje

3

這個函數

QJsonDocument看看:: fromJson(QByteArray)

http://doc.qt.io/qt-5/qjsondocument.html#fromJson

然後使用QJsonDocument::object(),您可以使用按鍵,讓您的值:

QJsonDocument doc = QJsonDocument::fromJson(QByteArray); 
QJsonObject root = doc.object(); 
foreach(QJsonValue element, root["CELLS"].toArray()){ 
    QJsonObject node = element.toObject(); 
    node["whatEver"]; 

}