Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Save QVector to JSON file



  • Hi guys,
    This code works but It'd be great if you could suggest a better code.

    "QVector<QPointF>" is the best choice for hold points? (I have a lot of points (more than 1,000,000 points) and a lot of processes on points)

    QJsonDocument JsonManager::vectorPointsToJsonDocument(QVector<QPointF> listPoints) {
        QVariantMap variantMap;
        for(int i=0;i<listPoints.size();i++){
            QJsonObject jsonObject;
            jsonObject["x"]=listPoints.at(i).x();
            jsonObject["y"]=listPoints.at(i).y();
            variantMap.insertMulti("point",jsonObject);
        }
        QJsonObject jsonObj=QJsonObject::fromVariantMap(variantMap);
    ...
    ...
    .....
    

  • Qt Champions 2019

    Take a look at QJsonArray and the Save Game example: http://doc.qt.io/qt-5/qtcore-serialization-savegame-example.html



  • @Christian-Ehrlicher
    Thanks a lot
    I see your link and write a new code.

    QJsonArray array;
        foreach(const QPointF point,listPoints){
            QJsonObject pointObject;
            pointObject["x"]=point.x();
            pointObject["y"]=point.y();
           array.append(pointObject);
        }
        QJsonObject object;
        object["points"] = array;
        QJsonDocument saveDoc(object);
        saveJson(saveDoc,fileName);
    


  • Hi. I spend some time making this small code to do a similar job in a different way. I hope someone can find it useful.

    #include <QCoreApplication>
    #include <iostream>
    #include <QVector>
    #include <QFile>
    #include <QJsonDocument>
    #include <QJsonValue>
    #include <QJsonArray>
    #include <QJsonObject>
    #include <QDateTime>
    
    QJsonDocument hacelawea(){
    
    //dummy vector
        QVector<int> mivector;
        for (int i=0;i<20;i++) {
            mivector.append(i);
        }
    
        QJsonArray jsonarray;
        foreach(const int i, mivector){
            QJsonValue Val(mivector[i]);
            jsonarray.append(Val);
        }
    
        QJsonObject objetofinal;
    
        objetofinal[QDateTime::currentDateTime().toString("yyyy-MM-dd'_'hh:mm:ss")]=jsonarray;
        QJsonDocument jasonsavedoc(objetofinal);
        return jasonsavedoc;
    
    }
    
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        std::cout<<"hola hola"<<std::endl;
    
        QFile saveFile(QStringLiteral("save.json"));
    
        if (!saveFile.open(QIODevice::ReadWrite)) {
            qWarning("Couldn't open save file.");
        }
    
        for(int i; i<5;i++)saveFile.write(hacelawea().toJson());
    
        saveFile.close();
    
        //return a.exec();
        return 0;
    }
    
    
    
    
    

Log in to reply