代码如下 | 复制代码 |
#include <QCoreApplication> #include <QDebug> #include <QJsonDocument> #include <QByteArray> #include <QVariant> #include <QMap> #include <QString> #include <QJsonObject> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //对象转json字符串 QMap<QString, QVariant> newData = QMap<QString, QVariant>(); newData.insert("content", "i'm content"); newData.insert("number", "i'm number"); newData.insert("time", "i'm time"); QJsonDocument doc=QJsonDocument::fromVariant(QVariant(newData)); QByteArray jba=doc.toJson(); QString jsonString = QString(jba); qDebug() << "QMap<QString, QVariant>转环后的json字符串\n" << jsonString; //字符串转json对象 QByteArray njba = jsonString.toUtf8(); QJsonObject nobj = QJsonObject(QJsonDocument::fromJson(njba).object()); qDebug() << "字符串转换后的对象\n" << nobj.take("content").toString() << endl << nobj.take("number").toString() << endl << nobj.take("time").toString() << endl; return a.exec(); } |
时间: 2024-09-28 06:52:08