Search code examples
c++jsonqtserializationqlist

Serialization QList<MyObject> to JSON


I've problem, I tried searched online like convert QList to JSON, and send it to URL, but first, I don't found nothing about serialise QList<Myobject> to json with Qt and C++.

My not empty QList:

QList<User> lista;

my target is lista to JSON.

How to serialize it? I've saw online that QJson exists, but is an external compenent... there is a internal component within Qt 5.9?


Solution

  • an external compenent

    Qt has internal JSON support.

    First you need to provide a QJsonValue representation for the object itself, and then iterate the list and convert it to e.g. an array. Use QJsonDocument to convert it to text:

    // https://github.com/KubaO/stackoverflown/tree/master/questions/json-serialize-44567345
    #include <QtCore>
    #include <cstdio>
    
    struct User {
       QString name;
       int age;
       QJsonObject toJson() const {
          return {{"name", name}, {"age", age}};
       }
    };
    
    QJsonArray toJson(const QList<User> & list) {
       QJsonArray array;
       for (auto & user : list)
          array.append(user.toJson());
       return array;
    }
    
    int main() {
       QList<User> users{{"John Doe", 43}, {"Mary Doe", 44}};
       auto doc = QJsonDocument(toJson(users));
       std::printf("%s", doc.toJson().constData());
    }
    

    Output:

    [
        {
            "age": 43,
            "name": "John Doe"
        },
        {
            "age": 44,
            "name": "Mary Doe"
        }
    ]