序列化 QList<MyObject> 到 JSON

Serialization QList<MyObject> to JSON

我有问题,我尝试在线搜索将 QList 转换为 JSON,然后将其发送到 URL,但首先,我没有找到任何关于序列化 QList<Myobject> 到 json 使用 Qt 和 C++。

我不为空QList

QList<User> lista;

我的目标是 JSON。

如何序列化?我在网上看到 QJson 存在,但它是一个外部组件...Qt 5.9 中有一个内部组件吗?

我认为一个简单的解决方案是将 JSON 对象创建为 QString。为此,您可以实现 QString User::toJson(),它会为您提供一个 JSON 有效字符串。然后你可以用 foreach 迭代你的 QList :

QString finalString ="";

foreach(User user, lista) {
   finalString += user.toJson();
   // Something like that...
}

return finalString;

an external compenent

Qt has internal JSON support.

首先您需要为对象本身提供一个 QJsonValue 表示,然后迭代列表并将其转换为例如数组。使用 QJsonDocument 将其转换为文本:

// https://github.com/KubaO/Whosebugn/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());
}

输出:

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