我终于找到了一个路径文件QFile将接受使用QFile.exist()和一个健康剂量的尝试和错误。
我想知道为什么会发生以下情况:
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
QString path = QDir::currentPath(); // Get current dir
path.append("/noteLibrary.json");
QFile file(path); // Give QFile current dir + path to file
if (!file.exists()) { // Check to see if QFile found the file at given file_path
qDebug() << "NO FILE HERE";
}
qDebug() << path; // See what path was finally successful
file.open(QIODevice::ReadOnly); // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
qDebug() << json["die"].toString(); // Should output "280C4"成功产出:
"/home/pi/noteLibrary.json"
"280C4"但下列各点不起作用:
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
QFile file("/home/pi/noteLibrary.json"); // Give QFile current dir + path to file
if (!file.exists()) { // Check to see if QFile found the file at given file_path
qDebug() << "NO FILE HERE";
}
//qDebug() << path; // See what path was finally successful
file.open(QIODevice::ReadOnly); // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
qDebug() << json["die"].toString(); // Should output "280C4"错误输出:
NO FILE HERE
QIODevice::read (QFile, "/home/pi/Desktop/noteLibrary.json"): device not open
""为什么QFile会以不同的方式对待这些呢?这是QString格式问题吗?或者我把这个远程部署到一个Raspberry Pi 3上的事实是否应该归咎于此呢?
发布于 2017-01-10 14:36:33
不管我上面的代码有什么问题,下面的代码为QFile提供了绝对路径,与使用currentPath()创建QString一样有效。我一定是出了别的错,我的错!
noteLibrary.json
{"note": [{
"profile": "C4",
"die": "280C4",
"pressure": 800,
"position": 10000
},
{
"profile": "CC4",
"die": "2280C4",
"pressure": 8800,
"position": 110000
}
],
"test": {
"profile": "CCC4",
"die": "22280C4",
"pressure": 88800,
"position": 1110000
}
}main.cpp节选
QFile file("/home/pi/noteLibrary.json");
if (!file.exists()) qDebug() << "NO FILE FOUND";
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
QJsonDocument doc(QJsonDocument::fromJson(rawData)); // Parse document
QJsonObject jObj = doc.object(); // Get JSON object
qDebug() << jObj["test"];应用输出
QJsonValue(object,QJsonObject({"die":"22280C4","position":1110000,"pressure":88800,"profile":"CCC4"}))它以字母顺序显示属性值,而不是按文档中列出的顺序显示,这似乎很奇怪。
https://stackoverflow.com/questions/41559426
复制相似问题