QVariantMap map; map.insert("name", "John"); map.insert("age", 30); QJsonDocument doc(QJsonObject::fromVariantMap(map)); QString jsonString = doc.toJson(); // Output: {"age":30,"name":"John"}
QVariantList list = {"apple", "banana", "cherry"}; QJsonDocument doc(QJsonArray::fromVariantList(list)); QString jsonString = doc.toJson(); // Output: ["apple","banana","cherry"]In this example, we create a QVariantList object with three elements. We convert this list to a QJsonArray and create a QJsonDocument with it. Finally, we call the toJson method to serialize the QJsonDocument to a JSON string. The QJsonDocument toJson function is part of the Qt JSON module, which is included in the Qt Core library.