如何解析这个 JSON 文件? (Qt)
Posted
技术标签:
【中文标题】如何解析这个 JSON 文件? (Qt)【英文标题】:How to parse this JSON file? (Qt) 【发布时间】:2020-02-04 11:51:38 【问题描述】:我正在使用 Qt5.7.1 并尝试读取我的 JSON 文件中的信息。 我的文件结构包括:配置名称、神经元个数、神经元数组(每个神经元都有严格数量的感受器和突触,也用数组表示)以及每个神经元的系数值他们。 我需要得到这些值。 我有这个 JSON 文件:
"Task config name": "Test",
"Configuration":
"NeuronsCount": 2,
"Neurons": [
"ReceptorsCount": 3,
"Receptors": [
"coef1": 17.32,
"coef2": 11.992,
"coef3": 2.314
,
"coef1": 12.982,
"coef2": 96.148,
"coef3": -1.899
,
"coef1": 49.11,
"coef2": 35.001,
"coef3": -643.52
],
"SynapsysCount": 4,
"Synapses": [
"coef1": 13.22,
"coef2": 31.992,
"coef3": 22.314
,
"coef1": 12.81,
"coef2": 36.8,
"coef3": -53.189
,
"coef1": 1.11,
"coef2": 44.261,
"coef3": -23.12
,
"coef1": 642.86,
"coef2": 24.24,
"coef3": 95.009
]
,
"ReceptorsCount": 3,
"Receptors": [
"coef1": 6.32,
"coef2": 64.992,
"coef3": 98.314
,
"coef1": 42.982,
"coef2": 11.148,
"coef3": -12.899
,
"coef1": 1.11,
"coef2": 752.001,
"coef3": -3.82
],
"SynapsysCount": 4,
"Synapses": [
"coef1": 19.82,
"coef2": 1.592,
"coef3": 75.384
,
"coef1": 89.81,
"coef2": 65.8,
"coef3": -13.189
,
"coef1": 18.11,
"coef2": 11.261,
"coef3": -211.12
,
"coef1": 2.86,
"coef2": 8.24,
"coef3": 6.009
]
]
如何接收每个“受体”和“突触”的 coef# 值? 我试过了,但它返回 0.. 如何读取这样的文件?
QByteArray data = jsonFile.readAll();
QJsonDocument document;
document = document.fromJson(data);
QJsonObject jsonObject = document.object();
QJsonArray neuronsArray = jsonObject.value("Neurons").toArray();
qDebug() << "Size = " << neuronsArray.size();
【问题讨论】:
【参考方案1】:您必须遍历 JSON 文档:
QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
QJsonObject root = doc.object();
QJsonObject conf = root.value("Configuration").toObject();
//this gives you the neurons array, in there you have objects which you can access just like above
QJsonArray arr = conf.value("Neurons").toArray();
【讨论】:
以上是关于如何解析这个 JSON 文件? (Qt)的主要内容,如果未能解决你的问题,请参考以下文章