QJsonDocument,QJsonObject,QJsonArray

 QJsonObject数据解析

//{
//	"Class": "class1", 
//	"Data" :
//	{
//		"Name": "Tom",
//		"Age" : 12,
//		"Array": [2, 3, 5, 8]
//	}	
//}
    
    // 这里的ba就是上面注释掉的这个json数据
	QByteArray ba = "{\"Class\": \"class1\", \"Data\" :{\"Name\": \"Tom\",\"Age\" : 12, \"Array\": [2, 3, 5, 8]}}";
	QJsonDocument doc = QJsonDocument::fromJson(ba);
	if (doc.isArray())
		qDebug() << "isArray";
	if (doc.isObject())
	{
		qDebug() << "isObject";
		QJsonObject obj = doc.object();
		QString className = obj.value("Class").toString();
		QJsonObject objData = obj.value("Data").toObject();
		foreach(QString key, objData.keys())
		{
			if (key == "Name")
			{
				QString name = objData.value(key).toString();
				qDebug() << "name = " << name;
			}
			else if (key == "Age")
			{
				bool b = objData.value(key).toInt();
				qDebug() << "b = " << b;
			}
			else if (key == "Array")
			{
				QJsonArray array = objData.value(key).toArray();
				qDebug() << "array = " << array;
				QVariantList list = array.toVariantList();
				qDebug() << "list = " << list;
			}
		}
	}

// 输出如下:
// isObject
// b =  true
// array =  QJsonArray([2,3,5,8])
// list =  (QVariant(double, 2), QVariant(double, 3), QVariant(double, 5), QVariant(double, 8))
// name =  "Tom"

QJsonObject 转 QByteArray:

QJsonDocument document;
QJsonObject obj;
obj.insert(password, "pwd");
obj.insert(userName, "usr");
document.setObject(obj);
QByteArray abyte = document.toJson(QJsonDocument::Compact);

QByteArray 转 QJsonObject:

QByteArray ba = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(ba);
QJsonObject obj = doc.object();

参考链接:链接

你可能感兴趣的:(Qt,QtClass,qt)