如何使用QJSONARRAY在QT5(C )中解析JSON文件(数组)
How to parsing JSON file(Array) in Qt5 (C++), using QJsonArray
我正在tring qt5。我尝试从JSON文件读取值。JSON文件就像上面的文件:
test.json
[{"w":188,"h":334,"th":0.350000,"l":232,"r":420,"t":133,"b":467,"p":0.713963,"n":"person"}]
[{"w":127,"h":141,"th":0.350000,"l":1152,"r":1279,"t":162,"b":303,"p":0.408129,"n":"person"},{"w":179,"h":339,"th":0.350000,"l":230,"r":409,"t":131,"b":470,"p":0.698172,"n":"person"}]
我尝试的是代码。如何读取这样的JSON文件结构?
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
//file is readall
val = file.readAll();
file.close();
qWarning() << val; //print consol
QJsonDocument jsonDocument = QJsonDocument::fromJson(val.toUtf8());
//get data array !!!
QJsonObject jsonObject = jsonDocument.object();
QJsonArray jsonArray = jsonObject["w"].toArray();
qWarning() << jsonArray[0].toString();
由于数据没有JSON格式(它是不形式的,请参见RFC 7159(,但是如果它是部分的,我们必须做的就是将其分开,因为我们使用QRegularExpresion
,并验证数据是否具有适当的格式,然后代码类似于您的代码。
代码:
#include <QCoreApplication>
#include <QFile>
#include <QDebug>
#include <QRegularExpression>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
QFile file("test.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qWarning() << "Could not open file!";
return 0;
}
const auto& data = QString(file.readAll());
file.close();
QRegularExpression regex("\[|\]");
const auto& jsons = data.split(regex);
for(const auto& json : jsons)
if(!json.trimmed().isEmpty()){
const auto& formattedJson = QString("[%1]").arg(json);
const auto& doc = QJsonDocument::fromJson(formattedJson.toUtf8());
if(doc.isArray())
for(const auto& item : doc.array()){
const auto& obj = item.toObject();
const auto& keys = obj.keys();
for(const auto& key : keys){
if(key == "n")
qDebug() << key << obj[key].toString();
else
qDebug() << key << obj[key].toInt();
}
}
}
return a.exec();
}
输出:
"b" 467
"h" 334
"l" 232
"n" "person"
"p" 0
"r" 420
"t" 133
"th" 0
"w" 188
"b" 303
"h" 141
"l" 1152
"n" "person"
"p" 0
"r" 1279
"t" 162
"th" 0
"w" 127
"b" 470
"h" 339
"l" 230
"n" "person"
"p" 0
"r" 409
"t" 131
"th" 0
"w" 179
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- 使用 Qt 解析 JSON 数组
- 在 C++ 中访问 JSON 数组值
- 无法使用 Poco 库正确克隆 JSON 数组C++
- 获取嵌套的 JSON 数组和矩阵C++
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- JSONCPP 只用一个元素写入 JSON 数组
- 如何打印 JSON 数组
- 在C++中使用 RapidJSON 访问 JSON 数组的字段
- 从QT的Web服务中解析未命名的JSON数组
- 使用 boost 读取复杂的 JSON 数组
- 创建 Qstring 的 Json 数组
- 在 qt c++ 中获取 Json 数组中 Qstring 的输出
- 如何使用 QT 创建 JSON 数组
- 如何将JSON数组存储在Arduino程序中
- C 返回函数的函数返回JSON数组通过Nlohmann Json.hpp
- 使用Boost C 创建JSON数组
- 从 JSON 数组获取天气
- 使用JSONCPP创建空的JSON数组
- C++ 将请求发送到 Web 服务器上的 API,然后接收 JSON 数组响应