Qt使用QJson生成json文件并保存

#include 
#include 
#include 
#include 
#include 
#include 
#include 

void createJson()
{
	QVariantHash data;

	QVariantHash subData1;
	subData1.insert("name", "apple");
	subData1.insert("icon", "appleIcon");
	subData1.insert("describe", "an apple");

	data.insert("first fruit", subData1);

	QVariantHash subData2;
	subData2.insert("name", "orange");
	subData2.insert("icon", "orangeIcon");
	subData2.insert("describe", "an orange");
	data.insert("second fruit", subData2);

	QJsonArray array1;
	for (int i = 0; i < 5; i++)
	{
		array1.insert(i, QString::fromLocal8Bit("eat %1").arg(i));
	}

	data.insert("three fruit array", array1);

	QJsonObject rootObj = QJsonObject::fromVariantHash(data);
	QJsonDocument document;
	document.setObject(rootObj);

	QByteArray byte_array = document.toJson(QJsonDocument::Compact);
	QString json_str(byte_array);
	//根据实际填写路径
	QFile file("D:\\1.json");

	if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
	{
		qDebug() << "file error!";
	}
	QTextStream in(&file);
	in << json_str;

	file.close();   // 关闭file
}

 

你可能感兴趣的:(Qt)