我希望将我的数据存储在JSON文件中,如:
{
"plottingData": [
{
"min": 17,
"max": 35,
"mean": 20
},
{
"min": 7,
"max": 35,
"mean": 17
},
{
"min": 8,
"max": 50,
"mean": 29
}
]
}
如何创建此结构? 我曾经使用过QJsonObject,但我无法像这样添加QJsonArray。
答案 0 :(得分:4)
来自Qt文档:
QJsonArray plot_array;
// use initializer list to construct QJsonObject
auto data1 = QJsonObject(
{
qMakePair(QString("min"), QJsonValue(17)),
qMakePair(QString("max"), QJsonValue(35)),
qMakePair(QString("mean"), QJsonValue(20))
});
plot_array.push_back(QJsonValue(data1));
// Or use insert method to create your QJsonObject
QString min_str("min");
QString max_str("max");
QString mean_str("mean");
for(auto item : your_collection)
{
QJsonObject item_data;
item_data.insert(min_str, QJsonValue(item.min));
item_data.insert(max_str, QJsonValue(item.max));
item_data.insert(mean_str, QJsonValue(item.mean));
plot_array.push_back(QJsonValue(item_data));
}
QJsonObject final_object;
final_object.insert(QString("plottingData"), QJsonValue(plot_array));
答案 1 :(得分:0)
QJsonObject o1
{
{ "min", 17 },
{ "max", 35 },
{ "mean", 20 },
};
QJsonObject o2;
o2 [ "min" ] = 7;
o2 [ "max" ] = 35;
o2 [ "mean"] = 17;
QJsonArray arr;
arr.append ( o1 );
arr.append ( o2 );
QJsonObject obj;
obj [ "plottingData" ] = arr;
//to see the JSON output
QJsonDocument doc ( obj );
qDebug() << doc.toJson ( QJsonDocument::Compact ); // or QJsonDocument::Indented
// output: "{\"plottingData\":[{\"max\":35,\"mean\":20,\"min\":17},{\"max\":35,\"mean\":17,\"min\":7}]}"