How to convert a QJsonObject to QString

雨燕双飞 提交于 2019-12-18 11:03:21

问题


I have a QJsonObject data and want to convert to QString. How can I do this? Searched for help in Qt, it only can convert QJsonObject to QVariantMap...

Thanks in advance.


回答1:


Remembering when I first needed to do this, the documentation can be a bit lacking and assumes you have knowledge of other QJson classes.

To obtain a QString of a QJsonObject, you need to use the QJsonDocument class, like this: -

QJsonObject jsonObj; // assume this has been populated with Json data

QJsonDocument doc(jsonObj);
QString strJson(doc.toJson(QJsonDocument::Compact));



回答2:


When the macro QT_NO_CAST_FROM_ASCII is enabled, you can do something like:

QJsonDocument doc(jsonObject);
QByteArray docByteArray = doc.toJson(QJsonDocument::Compact);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
Qstring strJson = codec->toUnicode(docByteArray);

Or better, just use QLatin1String(QByteArray&), based on the example of TheDarkKnight:

QJsonDocument doc(jsonObj);
QByteArray docByteArray = doc.toJson(QJsonDocument::Compact);
Qstring strJson = QLatin1String(docByteArray);


来源:https://stackoverflow.com/questions/28181627/how-to-convert-a-qjsonobject-to-qstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!